Elasticsearch-DSL(queries) 003

1.QUERY

首先須要從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')])

2.QUERY COMBINATION

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)
相關文章
相關標籤/搜索