2017-02-16 55 views
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中找到任何有关查询生成的内容。你们怎么做?任何投入都欢迎!

+1

你应该为了构建使用[Python的DSL(https://github.com/elastic/elasticsearch-dsl-py/)的正确方法是你的根据您获得的输入动态查询。 – Val

回答