大家好:
很长一段时间以来,我一直试图使用ElasticSearch-dsl Search()类复制这个查询,但不幸的是,我没有能够得到它。
我想复制的查询是:
{
"_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"
}
}
}
]
}
}
}其中的datetimes最终将被一个变量所取代。
到目前为止,我唯一能做的就是:
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())}})\我知道我离我想要的很远,所以如果有人能帮我的话,我会很感激。
发布于 2019-03-15 20:37:58
在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'])其次,这些对在弹性搜索-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'])现在,如果我们回想一下 query的结构,它由布尔子句组成,每个子句都带有“类型化的出现”(必须、应该、must_not等等)。因为每个子句也是一个‘ 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中构造查询时,可以使用from_dict()类的elasticsearch_dsl.Search方法返回原始的dict表示。
https://stackoverflow.com/questions/55170612
复制相似问题