[英]How to select or retrieve only specific fields after elasticsearch query?
我可以查詢 elasticsearch 中的索引。 而且,現在我想將數據縮小到某些特定字段。 但是,我不斷收到錯誤。
這是我的查詢:
es = Elasticsearch(hosts="myhost", "port":0000)
search_body={
"bool":{
"filter":[
{"exists": {"field": "customer_name"}},
{"match_phrase": {"city": "chicago"}},
]
}
}
results = es.search(index="some_index", query=search_body)
到目前為止,我很容易得到結果。 但是,由於返回的字段太多,我想在將其轉換為 dataframe 之前只檢索特定字段。 我可以將其轉換為 dataframe 然后過濾,但這不是最佳選擇。
我嘗試將_source
和field
方法添加為:
search_body={
"bool":{
"filter":[
{"exists": {"field": "customer_name"}},
{"match_phrase": {"city": "chicago"}},
]
},
"_source":{"fields": {"includes":["customer_name", "city", "company", "company_address"] }}
}
和其他變體,例如,
"fields": {"includes":["customer_name", "city", "company", "company_address"] }
# or
"_source":{"includes":["customer_name", "city", "company", "company_address"] }
# and several others.
我不斷收到錯誤:
raise HTTP_EXCEPTIONS.get(status_code, TransportError)(
elasticsearch.exceptions.RequestError: RequestError(400, 'parsing_exception', '[bool] malformed query, expected [END_OBJECT] but found [FIELD_NAME]')
我跟着:
我在這里想念什么?
從 JSON 看來,您提供的_source
字段正在您的bool
查詢中。 相反,您應該將其結構如下:
search_body = {
"query": {
"bool": [
{...}
]
},
"_source": {
"includes": [...]
}
}
(免責聲明:我是 Python Elasticsearch 客戶端的維護者並為 Elastic 工作)
嘗試這個:
results = es.search(index="some_index", query=search_body, source_includes=[...])
代碼是最好的文檔(有時!)
主要問題是將“search_body”參數作為body
或query
傳遞。
如果我的“search_body”如下所示,我不能將其作為query
傳遞,因為查詢是我在索引上請求的特定“查詢”。 在此查詢上請求_source
會使請求不正確。
search_body={
"bool":{
"filter":[
{"exists": {"field": "customer_name"}},
{"match_phrase": {"city": "chicago"}},
]
},
"_source":{"fields": {"includes":["customer_name", "city", "company", "company_address"] }}
}
這將通過,因為請求實際上是作為正文傳遞的,其中包含“查詢”和另一個“_source”字段以對數據進行子集化。
es = Elasticsearch(hosts="myhost", "port":0000)
results = es.search(index="some_index", body=search_body)
這將失敗,因為我已請求將搜索作為查詢並再次要求對數據進行子集化。
es = Elasticsearch(hosts="myhost", "port":0000)
results = es.search(index="some_index", query=search_body)
如果我們的search_body
如下所示,則第二個請求將通過:
search_body={
"bool":{
"filter":[
{"exists": {"field": "customer_name"}},
{"match_phrase": {"city": "chicago"}},
]
}
}
但對於命名約定,密鑰應命名為“query_body”。
query_body={
"bool":{
"filter":[
{"exists": {"field": "customer_name"}},
{"match_phrase": {"city": "chicago"}},
]
}
}
並要求:
es = Elasticsearch(hosts="myhost", "port":0000)
results = es.search(index="some_index", query=query_body)
因此,應該理解query
和body
是在索引上請求數據的兩種不同方式。
注意:Python elasticsearch 客戶端可能很快會在其請求中棄用body
參數。 在這種情況下,讓我們看看如何對過濾/查詢的數據進行子集化。
希望它可以幫助別人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.