ElasticSearch-dsl 创建查询

ElasticSearch-dsl Create Query

大家好:

我已经尝试了很长时间来使用 ElasticSearch-dsl Search() 复制此查询class,但不幸的是我无法获得它。

我要复制的查询是:

{
    "_source": {
            "includes": [ "SendingTime","Symbol","NoMDEntries","*"]
        },
        "from" : 0, "size" : 10000,
  "query": {
    "bool": {
      "must": [
        {
            "range": {
            "SendingTime": {
              "gte": "Oct 3, 2018 08:00:00 AM",
              "lt": "Oct 3, 2018 02:00:59 PM"
            }
          }
        }
      ]
    }
  }
}

日期时间最终会被变量替换。

到目前为止我唯一能做的是:

search = Search(using=elastic_search, index="bcs-md-bmk-prod")\
    .query("bool", range= {"SendingTime" : {'gte': format_date(datetime.now() - relativedelta(days=1)), 'lt': format_date(datetime.now())}})\

我知道我离我想要的还很远,所以如果有人能帮助我,我将不胜感激。

在 elasticsearch-dsl 中有多种构造相同查询的方法,这是为了方便用户,但有时(可能经常)会让新用户更加困惑。

首先,每个原始查询和elasticsearch-dsl查询之间存在一对一的匹配。例如,以下是等价的:

# 1
'query': {
    'multi_match': {
        'query': 'whatever you are looking for',
        'fields': ['title', 'content', 'footnote']
    }
}
# 2
from elasticsearch_dsl.query import MultiMatch
MultiMatch(query='whatever you are looking for', fields=['title', 'content', 'footnote'])

其次,这些对在 elasticsearch-dsl 中是等价的:

# 1 - using a class
from elasticsearch_dsl.query import MultiMatch
MultiMatch(query='whatever you are looking for', fields=['title', 'content', 'footnote'])
# 2 - using Q shortcut
Q('multi_match', query='whatever you are looking for', fields=['title', 'content', 'footnote'])

# 1 - using query type + keyword arguments 
Q('multi_match', query='whatever your are looking for', fields=['title', 'content', 'footnote'])
# 2 - using dict representation
Q({'multi_match': {'query': 'whatever your are looking for', 'fields': ['title', 'content', 'footnote']}})

# 1 - using Q shortcut
q = Q('multi_match', query='whatever your are looking for', fields=['title', 'content', 'footnote'])
s.query(q)
# 2 - using parameters for Q directly
s.query('multi_match', query='whatever your are looking for', fields=['title', 'content', 'footnote'])

现在,如果我们回想一下 bool query, it consists of boolean clauses, each clause with a 'typed occurrence' (must, should, must_not, etc.). Since each clause is also a 'query' (in your case a range query) 的结构,它遵循与 'query' 相同的模式,这意味着它可以用 Q 快捷方式表示。

因此,我构造您的查询的方式是:

search = Search(using=elastic_search, index="bcs-md-bmk-prod")
          .query(Q('bool', must=[Q('range', SendingTime={"gte": "Oct 3, 2018 08:00:00 AM", "lt": "Oct 3, 2018 02:00:59 PM"})]))
          .source(includes=["SendingTime","Symbol","NoMDEntries","*"])

请注意,为简单起见,可以删除第一个 Q,使该行成为:

.query('bool', must=[Q('range', SendingTime={"gte": "Oct 3, 2018 08:00:00 AM", "lt": "Oct 3, 2018 02:00:59 PM"})])

但我会保留它以便更容易理解。随意在不同的表示之间进行权衡。

最后但同样重要的是,当您在 elasticsearch-dsl 中构造查询时遇到困难时,您始终可以使用 elasticsearch_dsl.Search class 的 from_dict() 方法回退到原始字典表示。