導入 es
from elasticsearch import Elasticsearch
創(chuàng)建索引
es = Elasticsearch()
result = es.indices.create(index='news', ignore=400)
print(result)
{'error': {'root_cause': [{'type': 'resource_already_exists_exception', 'reason': 'index [news/habhrfkzSey5_GR-WmZPYA] already exists', 'index_uuid': 'habhrfkzSey5_GR-WmZPYA', 'index': 'news'}], 'type': 'resource_already_exists_exception', 'reason': 'index [news/habhrfkzSey5_GR-WmZPYA] already exists', 'index_uuid': 'habhrfkzSey5_GR-WmZPYA', 'index': 'news'}, 'status': 400}
其中的 acknowledged 字段表示創(chuàng)建操作執(zhí)行成功
重復創(chuàng)建索引,會引發(fā) 400 錯誤,因此我們需要 ignore 參數(shù)來屏蔽 400 錯誤
es = Elasticsearch()
result = es.indices.create(index='news', ignore=400)
print(result)
{'error': {'root_cause': [{'type': 'resource_already_exists_exception', 'reason': 'index [news/habhrfkzSey5_GR-WmZPYA] already exists', 'index_uuid': 'habhrfkzSey5_GR-WmZPYA', 'index': 'news'}], 'type': 'resource_already_exists_exception', 'reason': 'index [news/habhrfkzSey5_GR-WmZPYA] already exists', 'index_uuid': 'habhrfkzSey5_GR-WmZPYA', 'index': 'news'}, 'status': 400}
刪除索引
es = Elasticsearch()
result = es.indices.delete(index='news', ignore=[400, 404])
print(result)
{'acknowledged': True}
這里也是使用了 ignore 參數(shù),來忽略 Index 不存在而刪除失敗導致程序中斷的問題
es = Elasticsearch()
result = es.indices.delete(index='faq', ignore=[400, 404])
print(result)
{'acknowledged': True}
插入數(shù)據(jù)
Elasticsearch 就像 MongoDB 一樣,在插入數(shù)據(jù)的時候可以直接插入結構化字典數(shù)據(jù)恍涂,插入數(shù)據(jù)可以調(diào)用 create() 方法
from elasticsearch import Elasticsearch
es = Elasticsearch()
es.indices.create(index='news', ignore=400)
data = {'title': '美國留給伊拉克的是個爛攤子嗎', 'url': 'http://view.news.qq.com/zt2011/usa_iraq/index.htm'}
result = es.create(index='news', doc_type='faq', id=1, body=data)
print(result)
{'_index': 'news', '_type': 'faq', '_id': '1', '_version': 1, 'result': 'created', '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 0, '_primary_term': 1}
首先聲明了一條新聞數(shù)據(jù) data,包括標題和鏈接植榕,然后通過調(diào)用 create() 方法插入了這條數(shù)據(jù)再沧,在調(diào)用 create() 方法時,我們傳入了四個參數(shù)尊残,index 參數(shù)代表了索引名稱炒瘸,doc_type 代表了文檔類型,body 則代表了文檔具體內(nèi)容寝衫,id 則是數(shù)據(jù)的唯一標識 ID
結果中 result 字段為 created顷扩,代表該數(shù)據(jù)插入成功
我們也可以使用 index() 方法來插入數(shù)據(jù),但與 create() 不同的是竞端,create() 方法需要我們指定 id 字段來唯一標識該條數(shù)據(jù)屎即,而 index() 方法則不需要,如果不指定 id事富,會自動生成一個 id
es.index(index='news', body=data)
{'_index': 'news',
'_type': '_doc',
'_id': '33Fm1W4BMbliRpYyFApv',
'_version': 1,
'result': 'created',
'_shards': {'total': 2, 'successful': 1, 'failed': 0},
'_seq_no': 1,
'_primary_term': 1}
create() 方法內(nèi)部其實也是調(diào)用了 index() 方法技俐,是對 index() 方法的封裝
更新數(shù)據(jù)
更新數(shù)據(jù)需要指定數(shù)據(jù)的 id 和內(nèi)容,調(diào)用 update() 方法即可
不知道為什么一直會報錯统台,沒想明白原因雕擂,求大佬們指點迷津
es = Elasticsearch()
data = {'title': '美國留給伊拉克的是個爛攤子嗎', 'url': 'http://view.news.qq.com/zt2011/usa_iraq/index.htm', 'date': '2019'}
result = es.update(index='news', doc_type='faq', body=data, id=1)
print(result)
---------------------------------------------------------------------------
RequestError Traceback (most recent call last)
<ipython-input-9-769542d9ad85> in <module>
2
3 data = {'title': '美國留給伊拉克的是個爛攤子嗎', 'url': 'http://view.news.qq.com/zt2011/usa_iraq/index.htm', 'date': '2019'}
----> 4 result = es.update(index='news', doc_type='faq', body=data, id=1)
5 print(result)
/usr/local/lib/python3.7/site-packages/elasticsearch/client/utils.py in _wrapped(*args, **kwargs)
82 if p in kwargs:
83 params[p] = kwargs.pop(p)
---> 84 return func(*args, params=params, **kwargs)
85
86 return _wrapped
/usr/local/lib/python3.7/site-packages/elasticsearch/client/__init__.py in update(self, index, id, doc_type, body, params)
656 raise ValueError("Empty value passed for a required argument.")
657 return self.transport.perform_request(
--> 658 "POST", _make_path(index, doc_type, id, "_update"), params=params, body=body
659 )
660
/usr/local/lib/python3.7/site-packages/elasticsearch/transport.py in perform_request(self, method, url, headers, params, body)
356 headers=headers,
357 ignore=ignore,
--> 358 timeout=timeout,
359 )
360
/usr/local/lib/python3.7/site-packages/elasticsearch/connection/http_urllib3.py in perform_request(self, method, url, params, body, timeout, ignore, headers)
255 method, full_url, url, body, duration, response.status, raw_data
256 )
--> 257 self._raise_error(response.status, raw_data)
258
259 self.log_request_success(
/usr/local/lib/python3.7/site-packages/elasticsearch/connection/base.py in _raise_error(self, status_code, raw_data)
180
181 raise HTTP_EXCEPTIONS.get(status_code, TransportError)(
--> 182 status_code, error_message, additional_info
183 )
184
RequestError: RequestError(400, 'x_content_parse_exception', '[1:2] [UpdateRequest] unknown field [title], parser not found')
刪除數(shù)據(jù)
刪除一條數(shù)據(jù)可以調(diào)用 delete() 方法,指定需要刪除的數(shù)據(jù) id 即可
es = Elasticsearch()
result = es.delete(index='news', id=1)
print(result)
{'_index': 'news', '_type': '_doc', '_id': '1', '_version': 2, 'result': 'deleted', '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 2, '_primary_term': 1}
查詢數(shù)據(jù)
對于中文來說贱勃,我們需要安裝一個分詞插件井赌,這里使用的是 elasticsearch-analysis-ik谤逼,GitHub 鏈接為:https://github.com/medcl/elasticsearch-analysis-ik ,這里我們使用 Elasticsearch 的另一個命令行工具 elasticsearch-plugin 來安裝仇穗,這里安裝的版本是 7.0.1流部,請確保和 Elasticsearch 的版本對應起來,命令如下:
elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.0.1/elasticsearch
這里的版本號請?zhí)鎿Q成你的 Elasticsearch 的版本號
安裝之后重新啟動 Elasticsearch 就可以了纹坐,它會自動加載安裝好的插件
es = Elasticsearch()
mapping = {
'properties': {
'title': {
'type': 'text',
'analyzer': 'ik_max_word',
'search_analyzer': 'ik_max_word'
}
}
}
es.indices.delete(index='news', ignore=[400, 404])
es.indices.create(index='news', ignore=400)
result = es.indices.put_mapping(index='news', doc_type='faq', body=mapping, include_type_name=True)
print(result)
{'acknowledged': True}
這里我們先將之前的索引刪除了枝冀,然后新建了一個索引,然后更新了它的 mapping 信息耘子,mapping 信息中指定了分詞的字段果漾,指定了字段的類型 type 為 text,分詞器 analyzer 和 搜索分詞器 search_analyzer 為 ik_max_word谷誓,即使用我們剛才安裝的中文分詞插件绒障。如果不指定的話則使用默認的英文分詞器。
接下來我們插入幾條新的數(shù)據(jù)
datas = [
{
'title': '美國留給伊拉克的是個爛攤子嗎',
'url': 'http://view.news.qq.com/zt2011/usa_iraq/index.htm',
'date': '2011-12-16'
},
{
'title': '公安部:各地校車將享最高路權',
'url': 'http://www.chinanews.com/gn/2011/12-16/3536077.shtml',
'date': '2011-12-16'
},
{
'title': '中韓漁警沖突調(diào)查:韓警平均每天扣1艘中國漁船',
'url': 'https://news.qq.com/a/20111216/001044.htm',
'date': '2011-12-17'
},
{
'title': '中國駐洛杉磯領事館遭亞裔男子槍擊 嫌犯已自首',
'url': 'http://news.ifeng.com/world/detail_2011_12/16/11372558_0.shtml',
'date': '2011-12-18'
}
]
for data in datas:
es.index(index='news', body=data)
根據(jù)關鍵詞查詢一下相關內(nèi)容
result = es.search(index='news')
print(result)
{'took': 2, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 4, 'relation': 'eq'}, 'max_score': 1.0, 'hits': [{'_index': 'news', '_type': 'faq', '_id': '4HFm1W4BMbliRpYyaAqj', '_score': 1.0, '_source': {'title': '美國留給伊拉克的是個爛攤子嗎', 'url': 'http://view.news.qq.com/zt2011/usa_iraq/index.htm', 'date': '2011-12-16'}}, {'_index': 'news', '_type': 'faq', '_id': '4XFm1W4BMbliRpYyaQoE', '_score': 1.0, '_source': {'title': '公安部:各地校車將享最高路權', 'url': 'http://www.chinanews.com/gn/2011/12-16/3536077.shtml', 'date': '2011-12-16'}}, {'_index': 'news', '_type': 'faq', '_id': '4nFm1W4BMbliRpYyaQoc', '_score': 1.0, '_source': {'title': '中韓漁警沖突調(diào)查:韓警平均每天扣1艘中國漁船', 'url': 'https://news.qq.com/a/20111216/001044.htm', 'date': '2011-12-17'}}, {'_index': 'news', '_type': 'faq', '_id': '43Fm1W4BMbliRpYyaQo6', '_score': 1.0, '_source': {'title': '中國駐洛杉磯領事館遭亞裔男子槍擊 嫌犯已自首', 'url': 'http://news.ifeng.com/world/detail_2011_12/16/11372558_0.shtml', 'date': '2011-12-18'}}]}}
可以看到返回結果會出現(xiàn)在 hits 字段里面捍歪,然后其中有 total 字段標明了查詢的結果條目數(shù)户辱,還有 max_score 代表了最大匹配分數(shù)
另外我們還可以進行全文檢索,這才是體現(xiàn) Elasticsearch 搜索引擎特性的地方
使用 Elasticsearch 支持的 DSL 語句來進行查詢糙臼,使用 match 指定全文檢索焕妙,檢索的字段是 title,內(nèi)容是“中國領事館”弓摘,搜索結果如下
import json
dsl = {
'query': {
'match': {
'title': '中國領事館'
}
}
}
es = Elasticsearch()
result = es.search(index='news', body=dsl)
print(json.dumps(result, indent=2, ensure_ascii=False))
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 2,
"relation": "eq"
},
"max_score": 3.7446182,
"hits": [
{
"_index": "news",
"_type": "faq",
"_id": "43Fm1W4BMbliRpYyaQo6",
"_score": 3.7446182,
"_source": {
"title": "中國駐洛杉磯領事館遭亞裔男子槍擊 嫌犯已自首",
"url": "http://news.ifeng.com/world/detail_2011_12/16/11372558_0.shtml",
"date": "2011-12-18"
}
},
{
"_index": "news",
"_type": "faq",
"_id": "4nFm1W4BMbliRpYyaQoc",
"_score": 0.60291106,
"_source": {
"title": "中韓漁警沖突調(diào)查:韓警平均每天扣1艘中國漁船",
"url": "https://news.qq.com/a/20111216/001044.htm",
"date": "2011-12-17"
}
}
]
}
}
這里我們看到匹配的結果有兩條,第一條的分數(shù)為 3.99痕届,第二條的分數(shù)為 0.64韧献,這是因為第一條匹配的數(shù)據(jù)中含有“中國”和“領事館”兩個詞,第二條匹配的數(shù)據(jù)中不包含“領事館”研叫,但是包含了“中國”這個詞锤窑,所以也被檢索出來了,但是分數(shù)比較低嚷炉。
因此可以看出渊啰,檢索時會對對應的字段全文檢索,結果還會按照檢索關鍵詞的相關性進行排序申屹,這就是一個基本的搜索引擎雛形