【问题标题】:How to generate queries and skip parts of queries in Elasticsearch?如何在 Elasticsearch 中生成查询并跳过部分查询?
【发布时间】:2017-02-16 21:12:31
【问题描述】:

我正在使用 Python 通过自定义查询来查询 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 输入的两个单词替换 {$name} 和 {$surname}:

'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 以便根据您获得的输入动态构建查询。

标签: python elasticsearch


【解决方案1】:

Python DSL 似乎是正确的做法https://github.com/elastic/elasticsearch-dsl-py/

【讨论】:

    猜你喜欢
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2017-10-26
    相关资源
    最近更新 更多