Elasticsearch(六)过滤器

  • Bool filter

    mustshouldmust_not三种逻辑操作;其中当仅存在should时则必须至少满足一个条件.

    GET /books/book/_search
    {
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "name": "python"
              }
            }
          ],
          "should": [
            {
              "match": {
                "title": "effective"
              }
            }
          ]
        }
      }
    }
  • Exists filter

    exists filter过滤搜索结果,使其必须存在某个指定的字段.

    # exists filter
    GET /books/book/_search
    {
    "query": {
      "exists": {
        "field": "name"
      }
    }
    }

Null值的讨论:

假如索引test中存在类型为test的如下文档:

{"user": ""} # 1
{"user": []} # 2
{"user": null} # 3
{"user": [null]} # 4
{"user": "-"} # 5
{"user": "foo"} # 6
{"person": "bar"} # 7

对于如下的查询,将会返回1、5、6三条数据.

默认情况下:2、3、4、7四种情况都被认为是null值而被过滤,最终不可被搜索.

GET /test/test/_search
{
  "query": {
    "exists": {
      "field": "user"
    }
  }
}

可以在创建索引前,通过设置mappingnull_value属性的值,从而让3、4这两种情况文档可被搜索.

  • Type filter

    返回指定type的文档.

    GET /books/_search
    {
      "query": {
        "type": {
          "value": "book"
        }
      }
    }
  • Match_all filter

    选中全部数据,相当于SQL语句中的select * from book.

    GET /books/_search
    {
      "query": {
        "type": {
          "value": "book"
        }
      }
    }
  • Query filter

    ANDOR两种逻辑

    GET /books/book/_search
    {
      "query": {
        "query_string": {
          "default_field": "name",
          "query": "python OR java"  # "python AND java"
        }
      }
    }
  • 结果排序

    默认按照相关度得分_score倒排,还可以通过sort针对特定字段正排(asc)和倒排(desc);另外还可以在sort中指定_last将无值的结果放在检索集的最后.

    GET /users/user/_search
    {
      "query": {
        "match": {
          "name": "bourne"
        }
      },
      "sort": [
        {
          "created_at": {
            "order": "desc",
            "missing": "_last"
          }
        }
      ]
    }

目录