现在我们已经看过了基础搜索参数,让我们深入挖掘一下Query DSL。首先让我们看一下返回文档的字段。默认情况下,搜索返回的是全量JSON文档。这杯称之为source(搜索返回值中hits的_source字段)。如果我们不想返回整个source文档,我们是可以请求只返回source中的某些字段的。
下面的例子展示了如何返回两个字段account_number和 balance(_source中的两个字段):

GET /bank/_search
{
"query": { "match_all": {} },
"_source": ["account_number", "balance"]
}

注意上面的例子只是简单的减少了_source中的字段,其仍会返回_source字段,但是在它内部,只包含了account_number和balance字段。

如果你以前有SQL的使用背景,上面的概念有些类似SQL的SELECT 字段列表 FROM 。

接下来让我们来看看查询。前面我们已经学习过如何使用match_all来查询所有的文档的。让我们引入另外一个关键字match查询,这是一个用于基础字段检索的条件关键字。(例如从指定的一个或一组字段中检索)。
下面的例子查询account的值等于20的文档:

GET /bank/_search
{
"query": { "match": { "account_number": 20 } }
}

 

 

下面的例子返回所有的address包含mill或lane的account记录:

GET /bank/_search
{
"query": { "match": { "address": "mill lane" } }
}

 

 

下面的例子是match的变种(match_phrase), 其将返回所有的address字段包含“mill lane”的accounts记录:

GET /bank/_search
{
"query": { "match_phrase": { "address": "mill lane" } }
}

 

 

现在我们来介绍bool(ean)布尔查询。bool查询允许我们使用布尔逻辑将小的查询组成大的(复杂的)的查询。
下面的例子组合了两个match查询,用于返回address字段包含mill或者lane的accounts记录:

GET /bank/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "address": "mill"
          }
        },
        {
          "match": {
            "address": "lane"
          }
        }
      ]
    }
  }
}

 

上面例子中的bool must表示所有的match条件必须都满足才被认为匹配了查询。
相比之下,下面的例子组合了两个match查询并返回address中包含mill或者lane的account记录:

GET /bank/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "address": "mill"
          }
        },
        {
          "match": {
            "address": "lane"
          }
        }
      ]
    }
  }
}

 

上面的例子中,bool should语句指定一组查询条件,任何一个条件满足,对应文档机会被作为匹配记录返回。

下面的例子组合了两个match查询,用于返回不包含mill或者lane的account记录:

GET /bank/_search
{
  "query": {
    "bool": {
      "must_not": [
        {
          "match": {
            "address": "mill"
          }
        },
        {
          "match": {
            "address": "lane"
          }
        }
      ]
    }
  }
}

 


上面的例子中,bool must_not所指定的条件中,任何一个都必须为false,对应的文档才被认为是匹配的记录。

我们可以在一个bool查询内部同时组合must,should以及must_not语句。而且我们可以在任何bool语句中包含bool查询来模拟复杂了多层级bool逻辑。

下面的例子返回所有年龄为40岁并且state不为ID的account记录:

GET /bank/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "age": "40"
          }
        }
      ],
      "must_not": [
        {
          "match": {
            "state": "ID"
          }
        }
      ]
    }
  }
}

 

 

 

 

本文系本人根据官方文档的翻译,能力有限、水平一般,如果对想学习Elasticsearch的朋友有帮助,将是本人的莫大荣幸。
原文出处:https://www.elastic.co/guide/en/elasticsearch/reference/current/_executing_searches.html

 posted on 2017-05-02 15:09  段子手6哥  阅读(182)  评论(0编辑  收藏  举报