首先须要从elasticsearch_dsl.query导入所须要的query类型 例如导入全部:python
from elasticsearch_dsl.query import *
下面是全部可导入的query:web
In [34]: from elasticsearch_dsl.query import Bool FunctionScore GeohashCell MatchPhrasePrefix Query SpanMulti Type Boosting Fuzzy HasChild Missing QueryString SpanNear Wildcard Common FuzzyLikeThis HasParent MoreLikeThis Range SpanNot _make_dsl_class ConstantScore FuzzyLikeThisField Ids MoreLikeThisField Regexp SpanOr params_def DisMax GeoBoundingBox Indices MultiMatch SF SpanTerm qclass DslBase GeoDistance Limit Nested ScoreFunction Template qname EMPTY_QUERY GeoDistanceRange Match Prefix Script Term Exists GeoPolygon MatchAll Q SimpleQueryString Terms Filtered GeoShape MatchPhrase QUERIES SpanFirst TopChildren
下面是匹配实例:django
# {"multi_match": {"query": "python django", "fields": ["title", "body"]}} MultiMatch(query='python django', fields=['title', 'body']) # {"match": {"title": {"query": "web framework", "type": "phrase"}}} Match(title={"query": "web framework", "type": "phrase"})
咱们能够用Q快捷方式使用一个带着参数或原字典的名字重写例子:elasticsearch
Q("multi_match", query='python django', fields=['title', 'body']) Q({"multi_match": {"query": "python django", "fields": ["title", "body"]}})
使用.query()方法把这个匹配添加到已存在的匹配项目:code
q = Q("multi_match", query='python django', fields=['title', 'body']) s = s.query(q)
这个方法接受全部的参数做为Q的快捷方法:ip
s = s.query("multi_match", query='python django', fields=['title', 'body'])
若是已经存在一个匹配项目,能够覆盖这个项目:hash
s.query = Q('bool', must=[Q('match', title='python'), Q('match', body='best')])
query能够经过逻辑操做连接it
Q("match", title='python') | Q("match", title='django') # {"bool": {"should": [...]}} Q("match", title='python') & Q("match", title='django') # {"bool": {"must": [...]}} ~Q("match", title="python") # {"bool": {"must_not": [...]}}
调用.query()屡次,&操做能够在内部使用:io
s = s.query().query() print(s.to_dict()) # {"query": {"bool": {...}}}
若是想要对query的格式有一个精确的控制,使用Q快捷方法直接重建combined query:ast
q = Q('bool', must=[Q('match', title='python')], should=[Q(...), Q(...)], minimum_should_match=1 ) s = Search().query(q)