elasticsearch 的 python API

導入 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 參數來屏蔽 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 參數,來忽略 Index 不存在而刪除失敗導致程序中斷的問題

es = Elasticsearch()
 
result = es.indices.delete(index='faq', ignore=[400, 404])
print(result)
{'acknowledged': True}

插入數據

Elasticsearch 就像 MongoDB 一樣,在插入數據的時候可以直接插入結構化字典數據,插入數據可以調用 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}

首先聲明了一條新聞數據 data,包括標題和鏈接,然后通過調用 create() 方法插入了這條數據,在調用 create() 方法時,我們傳入了四個參數,index 參數代表了索引名稱,doc_type 代表了文檔類型,body 則代表了文檔具體內容,id 則是數據的唯一標識 ID

結果中 result 字段為 created,代表該數據插入成功

我們也可以使用 index() 方法來插入數據,但與 create() 不同的是,create() 方法需要我們指定 id 字段來唯一標識該條數據,而 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() 方法內部其實也是調用了 index() 方法,是對 index() 方法的封裝

更新數據

更新數據需要指定數據的 id 和內容,調用 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')

刪除數據

刪除一條數據可以調用 delete() 方法,指定需要刪除的數據 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}

查詢數據

對于中文來說,我們需要安裝一個分詞插件,這里使用的是 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,即使用我們剛才安裝的中文分詞插件。如果不指定的話則使用默認的英文分詞器。

接下來我們插入幾條新的數據

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': '中韓漁警沖突調查:韓警平均每天扣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)

根據關鍵詞查詢一下相關內容

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': '中韓漁警沖突調查:韓警平均每天扣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'}}]}}

可以看到返回結果會出現在 hits 字段里面,然后其中有 total 字段標明了查詢的結果條目數,還有 max_score 代表了最大匹配分數

另外我們還可以進行全文檢索,這才是體現 Elasticsearch 搜索引擎特性的地方

使用 Elasticsearch 支持的 DSL 語句來進行查詢,使用 match 指定全文檢索,檢索的字段是 title,內容是“中國領事館”,搜索結果如下

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": "中韓漁警沖突調查:韓警平均每天扣1艘中國漁船",
          "url": "https://news.qq.com/a/20111216/001044.htm",
          "date": "2011-12-17"
        }
      }
    ]
  }
}

這里我們看到匹配的結果有兩條,第一條的分數為 3.99,第二條的分數為 0.64,這是因為第一條匹配的數據中含有“中國”和“領事館”兩個詞,第二條匹配的數據中不包含“領事館”,但是包含了“中國”這個詞,所以也被檢索出來了,但是分數比較低。

因此可以看出,檢索時會對對應的字段全文檢索,結果還會按照檢索關鍵詞的相關性進行排序,這就是一個基本的搜索引擎雛形

參考:https://blog.csdn.net/devcloud/article/details/91446259

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容