Elasticsearch 是一個開源的搜索引擎,建立在一個全文搜索引擎庫 Apache Lucene™ 基礎之上。 Lucene 可能是目前存在的,不論開源還是私有的,擁有最先進,高性能和全功能搜索引擎功能的庫。但是 Lucene 僅僅只是一個庫。為了利用它,你需要編寫 Java 程序,並在你的 java 程序里面直接集成 Lucene 包。 更壞的情況是,你需要對信息檢索有一定程度的理解才能明白 Lucene 是怎么工作的。Lucene 是 很 復雜的。
在上一篇博客中介紹了ElasticSearch的簡單使用,接下來記錄一下ElasticSearch的查詢:
安裝
pip install elasticsearch5 # 安裝對應版本的模塊
創建ES對象
from elasticsearch5 import Elasticsearch # elasticsearch集群服務器的地址 ES = [ '127.0.0.1:9200' ] # 創建elasticsearch客戶端 es = Elasticsearch( ES, # 啟動前嗅探es集群服務器 sniff_on_start=True, # es集群服務器結點連接異常時是否刷新es節點信息 sniff_on_connection_fail=True, # 每60秒刷新節點信息 sniffer_timeout=60 )
搜索數據
query = { 'query': { 'bool': { 'must': [ {'match': {'_all': 'python web'}} ], 'filter': [ {'term': {'status': 2}} ] } } } ret = es.search(index='articles', doc_type='article', body=query)
scan 迭代器查詢(不能用分組)
from elasticsearch5 import helpers query = { 'query': { 'bool': { 'should':[ {'match': {'aaa': '123'}}, ] } }, "_source": ["aaa", "bbb", "ccc", "ddd", "eee", "fff"], } #scroll='1m'查詢一次數據在ES中緩存5分鍾再銷毀 scanResp= helpers.scan(client= es, query=query, scroll= "1m", index= "abc-*" , doc_type= "doc" , timeout="1m") for resp in scanResp: _source = resp['_source'] aaa= _source['aaa']
#創建index索引
#創建索引,索引的名字是my-index,如果已經存在了,就返回個400, #這個索引可以現在創建,也可以在后面插入數據的時候再臨時創建 es.indices.create(index='my-index',ignore)
#插入數據
#插入數據,(這里省略插入其他兩條數據,后面用) es.index(index="my-index",doc_type="test-type",id=01,body={"any":"data01","timestamp":datetime.now()})
#get獲取數據
#查詢數據,兩種get and search #get獲取 res = es.get(index="my-index", doc_type="test-type", id=01) es.get(index='indexName', doc_type='typeName', id='idValue')
#刪除數據
delete:刪除指定index、type、id的文檔 es.delete(index='indexName', doc_type='typeName', id='idValue')
#條件刪除
delete_by_query:刪除滿足條件的所有數據,查詢條件必須符合DLS格式 query = {'query': {'match': {'sex': 'famale'}}}# 刪除性別為女性的所有文檔 query = {'query': {'range': {'age': {'lt': 11}}}}# 刪除年齡小於11的所有文檔 es.delete_by_query(index='indexName', body=query, doc_type='typeName')
#條件更新
update_by_query:更新滿足條件的所有數據,寫法同上刪除和查詢
#批量寫入、刪除、更新
doc = [ {"index": {}}, {'name': 'jackaaa', 'age': 2000, 'sex': 'female', 'address': u'北京'}, {"index": {}}, {'name': 'jackbbb', 'age': 3000, 'sex': 'male', 'address': u'上海'}, {"index": {}}, {'name': 'jackccc', 'age': 4000, 'sex': 'female', 'address': u'廣州'}, {"index": {}}, {'name': 'jackddd', 'age': 1000, 'sex': 'male', 'address': u'深圳'}, ] doc = [ {'index': {'_index': 'indexName', '_type': 'typeName', '_id': 'idValue'}} {'name': 'jack', 'sex': 'male', 'age': 10 } {'delete': {'_index': 'indexName', '_type': 'typeName', '_id': 'idValue'}} {"create": {'_index' : 'indexName', "_type" : 'typeName', '_id': 'idValue'}} {'name': 'lucy', 'sex': 'female', 'age': 20 } {'update': {'_index': 'indexName', '_type': 'typeName', '_id': 'idValue'}} {'doc': {'age': '100'}} ] es.bulk(index='indexName', doc_type='typeName', body=doc) #批量更新也可以采用如下的方式進行json拼裝,最后寫入 for line in list: action = { "_index": self.index_name, "_type": self.index_type, "_id": i, #_id 也可以默認生成,不賦值 "_source": { "date": line['date'], "source": line['source'].decode('utf8'), "link": line['link'], "keyword": line['keyword'].decode('utf8'), "title": line['title'].decode('utf8')} } i += 1 ACTIONS.append(action) success, _ = bulk(self.es, ACTIONS, index=self.index_name, raise_on_error=True)
查詢所有數據
搜索所有數據
es.search(index="my_index",doc_type="test_type") # 或者 body = { "query":{ "match_all":{} } } es.search(index="my_index",doc_type="test_type",body=body)
#term與terms
body = { "query":{ "term":{ "name":"python" } } } # 查詢name="python"的所有數據 es.search(index="my_index",doc_type="test_type",body=body)
terms
body = { "query":{ "terms":{ "name":[ "python","android" ] } } } # 搜索出name="python"或name="android"的所有數據 es.search(index="my_index",doc_type="test_type",body=body)
#match與multi_match
# match:匹配name包含python關鍵字的數據 body = { "query":{ "match":{ "name":"python" } } } # 查詢name包含python關鍵字的數據 es.search(index="my_index",doc_type="test_type",body=body) # multi_match:在name和addr里匹配包含深圳關鍵字的數據 body = { "query":{ "multi_match":{ "query":"深圳", "fields":["name","addr"] } } } # 查詢name和addr包含"深圳"關鍵字的數據 es.search(index="my_index",doc_type="test_type",body=body)
#ids
body = { "query":{ "ids":{ "type":"test_type", "values":[ "1","2" ] } } } # 搜索出id為1或2d的所有數據 es.search(index="my_index",doc_type="test_type",body=body)
#復合查詢bool
bool有3類查詢關系,must(都滿足),should(其中一個滿足),must_not(都不滿足)
body = { "query":{ "bool":{ "must":[ { "term":{ "name":"python" } }, { "term":{ "age":18 } } ] } } } # 獲取name="python"並且age=18的所有數據 es.search(index="my_index",doc_type="test_type",body=body)
#切片式查詢
body = { "query":{ "match_all":{} } "from":2 # 從第二條數據開始 "size":4 # 獲取4條數據 } # 從第2條數據開始,獲取4條數據 es.search(index="my_index",doc_type="test_type",body=body)
#范圍查詢
body = { "query":{ "range":{ "age":{ "gte":18, # >=18 "lte":30 # <=30 } } } } # 查詢18<=age<=30的所有數據 es.search(index="my_index",doc_type="test_type",body=body)
#前綴查詢
body = { "query":{ "prefix":{ "name":"p" #有問題
} } } # 查詢前綴為"趙"的所有數據 es.search(index="my_index",doc_type="test_type",body=body)
#通配符查詢
body = { "query":{ "wildcard":{ "name":"*id" } } } # 查詢name以id為后綴的所有數據 es.search(index="my_index",doc_type="test_type",body=body)
#排序
body = { "query":{ "match_all":{} } "sort":{ "age":{ # 根據age字段升序排序 "order":"asc" # asc升序,desc降序 } } }
#filter_path
響應過濾
# 只需要獲取_id數據,多個條件用逗號隔開 es.search(index="my_index",doc_type="test_type",filter_path=["hits.hits._id"]) # 獲取所有數據 es.search(index="my_index",doc_type="test_type",filter_path=["hits.hits._*"])
#count
執行查詢並獲取該查詢的匹配數
# 獲取數據量 es.count(index="my_index",doc_type="test_type")
#度量類聚合
獲取最小值
body = { "query":{ "match_all":{} }, "aggs":{ # 聚合查詢 "min_age":{ # 最小值的key "min":{ # 最小 "field":"age" # 查詢"age"的最小值 } } } } # 搜索所有數據,並獲取age最小的值 es.search(index="my_index",doc_type="test_type",body=body)
獲取最大值
body = { "query":{ "match_all":{} }, "aggs":{ # 聚合查詢 "max_age":{ # 最大值的key "max":{ # 最大 "field":"age" # 查詢"age"的最大值 } } } } # 搜索所有數據,並獲取age最大的值 es.search(index="my_index",doc_type="test_type",body=body)
獲取和
body = { "query":{ "match_all":{} }, "aggs":{ # 聚合查詢 "sum_age":{ # 和的key "sum":{ # 和 "field":"age" # 獲取所有age的和 } } } } # 搜索所有數據,並獲取所有age的和 es.search(index="my_index",doc_type="test_type",body=body)
獲取平均值
body = { "query":{ "match_all":{} }, "aggs":{ # 聚合查詢 "avg_age":{ # 平均值的key "sum":{ # 平均值 "field":"age" # 獲取所有age的平均值 } } } } # 搜索所有數據,獲取所有age的平均值 es.search(index="my_index",doc_type="test_type",body=body)
更多的搜索用法:
https://elasticsearch-py.readthedocs.io/en/master/api.html
趙