php 使用 ElasticSearch 高级查询、过滤、排序

一、高级查询

1. 布尔查询(bool)

bool把各种其它查询通过must(与)、must_not(非)、should(或)的方式进行组合。

GET /yoshop/_search
{
    "query":{
        "bool":{
          "must":     { "match": { "title": "大米" }},
          "must_not": { "match": { "title":  "电视" }},
          "should":   { "match": { "title": "手机" }}
        }
    }
}

2. 范围查询(range)

range 查询找出那些落在指定区间内的数字或者时间。

GET /heima/_search
{
    "query":{
        "range": {
            "price": {
                "gte":  1000.0,
                "lt":   2800.00
            }
      }
    }
}

3. 模糊查询(fuzzy)

fuzzy 查询是 term 查询的模糊等价。它允许用户搜索词条与实际词条的拼写出现偏差,但是偏差的编辑距离不得超过2。

GET /youshop/_search
{
    "query": {
      "fuzzy": {
        "title": "applo"
      }
    }
}

上面的查询,也能查询到apple手机

我们可以通过fuzziness来指定允许的编辑距离。

GET /youshop/_search
{
  "query": {
    "fuzzy": {
        "title": {
            "value":"appla",
            "fuzziness":1
        }
    }
  }
}

二、过滤(filter)

filter方式是在查询结果中进行过滤的,不会影响评分。

GET /youshop/_search
{
    "query":{
        "bool":{
          "must":{ "match": { "title": "小米手机" }},
          "filter":{
                "range":{"price":{"gt":3000,"lt":3800.00}}
          }
        }
    }
}

注意:filter中还可以再次进行bool组合条件过滤。

三、排序

1. 单字段排序

sort 可以让我们按照不同的字段进行排序,并且通过order指定排序的方式。

GET /youshop/_search
{
  "query": {
    "match": {
      "title": "小米手机"
    }
  },
  "sort": [
    {
      "price": {
        "order": "desc"
      }
    }
  ]
}

2. 多字段排序

假定我们想要结合使用 price和_id进行查询,并且匹配的结果首先按照价格排序,然后按照相id排序。

GET /goods/_search
{
    "query":{
        "bool":{
          "must":{ "match": { "title": "小米手机" }},
          "filter":{
                "range":{"price":{"gt":2000,"lt":3000}}
          }
        }
    },
    "sort": [
      { "price": { "order": "desc" }},
      { "_id": { "order": "desc" }}
    ]
}

918eb2075a67416087e73734d343c70b.jpeg

猜你喜欢

转载自blog.csdn.net/lxw1844912514/article/details/132074272