Queries vs. Filters

前端 未结 8 843
太阳男子
太阳男子 2020-11-29 15:20

I can\'t see any description of when I should use a query or a filter or some combination of the two. What is the difference between them? Can anyone please explain?

8条回答
  •  甜味超标
    2020-11-29 15:33

    An example (try it yourself)

    Say index myindex contains three documents:

    curl -XPOST localhost:9200/myindex/mytype  -d '{ "msg": "Hello world!" }'
    curl -XPOST localhost:9200/myindex/mytype  -d '{ "msg": "Hello world! I am Sam." }'
    curl -XPOST localhost:9200/myindex/mytype  -d '{ "msg": "Hi Stack Overflow!" }'
    

    Query: How well a document matches the query

    Query hello sam (using keyword must)

    curl localhost:9200/myindex/_search?pretty  -d '
    {
      "query": { "bool": { "must": { "match": { "msg": "hello sam" }}}}
    }'
    

    Document "Hello world! I am Sam." is assigned a higher score than "Hello world!", because the former matches both words in the query. Documents are scored.

    "hits" : [
       ...
         "_score" : 0.74487394,
         "_source" : {
           "name" : "Hello world! I am Sam."
         }
       ...
         "_score" : 0.22108285,
         "_source" : {
           "name" : "Hello world!"
         }
       ...
    

    Filter: Whether a document matches the query

    Filter hello sam (using keyword filter)

    curl localhost:9200/myindex/_search?pretty  -d '
    {
      "query": { "bool": { "filter": { "match": { "msg": "hello sam" }}}}
    }'
    

    Documents that contain either hello or sam are returned. Documents are NOT scored.

    "hits" : [
       ...
         "_score" : 0.0,
         "_source" : {
           "name" : "Hello world!"
         }
       ...
         "_score" : 0.0,
         "_source" : {
           "name" : "Hello world! I am Sam."
         }
       ...
    

    Unless you need full text search or scoring, filters are preferred because frequently used filters will be cached automatically by Elasticsearch, to speed up performance. See Elasticsearch: Query and filter context.

提交回复
热议问题