2017-07-27 131 views
0

我在elasticsearch中有一個JSON文件列表。elasticsearch查詢 - 兩個條件

我有一個字符串列表matching,我想用它作爲搜索條件。

其中,matching = ["223232_ds","dnjsnsd_22","2ee2i33","mkddsj2220","23e3efdjn"

我現在需要找到elasticsearch那些記錄,兩個鍵包含在這份名單中,matching值。

沒有elasticsearch,只需加載JSON作爲一個Python對象,我可以做到這一點,如:

results= [] 
for record in JSON_list: 
    if record['key_1'] in matching and record['key_2'] in matching: 
      results.append(record) 

JSON_list看起來是這樣的:

[{'key_1' : "blahaksds", 
'key_2' : "njasdnjkns"}, 
{'key_1' : "bladfgfdf", 
'key_2' : "njasdsfsdrr"}] 

如何搜索在多個條件ES?以前,我使用此設置直接搜索record_id。

es = elasticsearch.Elasticsearch() 

name = "so_sample" 

# Formulate query 
query = str("_id:"+'"'+ record_id +'"') 

# Query 
result = es.search(name,q=query) 

回答

0

可以必備子句中使用兩個terms queriesbool query,就像這樣:

{ 
    "query": { 
    "bool": { 
     "must": [ 
     { 
      "terms": { 
      "key_1": ["223232_ds","dnjsnsd_22","2ee2i33","mkddsj2220","23e3efdjn"] 
      } 
     }, 
     { 
      "terms": { 
      "key_2": ["223232_ds","dnjsnsd_22","2ee2i33","mkddsj2220","23e3efdjn"] 
      } 
     } 
     ] 
    } 
    } 
}