0
我正在使用Python通過自定義查詢來查詢Elasticsearch。讓我們來看看一個非常簡單的例子,將在該領域「名稱」的特定期限和另外一個在文檔的「姓」字段進行搜索:如何在Elasticsearch中生成查詢並跳過部分查詢?
from elasticsearch import Elasticsearch
import json
# read query from external JSON
with open('query.json') as data_file:
read_query= json.load(data_file)
# search with elastic search and show hits
es = Elasticsearch()
# set query through body parameter
res = es.search(index="test", doc_type="articles", body=read_query)
print("%d documents found" % res['hits']['total'])
for doc in res['hits']['hits']:
print("%s) %s" % (doc['_id'], doc['_source']['content']))
「query.json」
{
"query": {
"bool": {
"should": [
{
"match": {
"name": {
"query": "Star",
"boost": 2
}
}
},
{
"match": {
"surname": "Fox"
}
}
]
}
}
}
現在,我期待用戶輸入搜索詞,輸入的第一個單詞用於字段'名稱',第二個單詞用於'姓'。讓我們想象一下,我將使用python與已經由用戶鍵入這兩個詞替換{$名稱}和{$姓}:
'query.json'
{
"query": {
"bool": {
"should": [
{
"match": {
"name": {
"query": "{$name}",
"boost": 2
}
}
},
{
"match": {
"surname": "{$surname}"
}
}
]
}
}
}
現在,當用戶不輸入姓氏出現問題但只有名字,所以我結束了以下查詢:
'query.json'
{
"query": {
"bool": {
"should": [
{
"match": {
"name": {
"query": "Star",
"boost": 2
}
}
},
{
"match": {
"surname": ""
}
}
]
}
}
}
字段「姓」現在是空的,並elasticsearch會尋找命中,其中「姓」是一個空字符串,這是不是我想要的。如果輸入項爲空,我想忽略姓氏字段。如果給定的項是空的,elasticsearch中是否有任何機制可以將查詢的一部分設置爲忽略?
{
"query": {
"bool": {
"should": [
{
"match": {
"name": {
"query": "Star",
"boost": 2
}
}
},
{
"match": {
"surname": "",
"ignore_if_empty" <--- this would be really cool
}
}
]
}
}
}
也許有任何其他的方式來生成查詢字符串?我似乎無法在Elasticsearch中找到任何有關查詢生成的內容。你們怎麼做?任何投入都歡迎!
你應該爲了構建使用[Python的DSL(https://github.com/elastic/elasticsearch-dsl-py/)的正確方法是你的根據您獲得的輸入動態查詢。 – Val