ES学习之DSL Match

1.match query对查询条件先进行分词,使用和被查字段相同的分词法

get /index1/_search{
    "query":{
        "match":{
            "name":"jack chen"   //查询前会分词为jack,chen两个term,然后去倒排索引查找
        }
    }
}

下面是查找到的结果,只要包含查询条件中的一个term就符合搜索,命中term越多,关联得分越高。

"hits" : [
      {
        "_index" : "index1",
        "_id" : "3",
        "_score" : 0.78038335,
        "_source" : {
          "name" : "jack chen"
        }
      },
      {
        "_index" : "index1",
        "_id" : "2",
        "_score" : 0.52354836,
        "_source" : {
          "name" : "chen",
          "age" : 20
        }
      },
      {
        "_index" : "index1",
        "_id" : "1",
        "_score" : 0.52354836,
        "_source" : {
          "name" : "jack",
          "age" : 10
        }
      }
    ]

如果我们指定要包含所有term的文档,可以使用operator参数来控制

get /index1/_search
{
  "query":{
    "match": {
      "name": {
        "query": "chen jack",
        "operator": "and"  //表明文档必须同时含有chen,jack  顺序无关
      }
    }
  }
}

结果如下

"hits" : [
      {
        "_index" : "index1",
        "_id" : "3",
        "_score" : 0.78038335,
        "_source" : {
          "name" : "jack chen"
        }
      }
    ]

同时,也可以使用minimu_should_match来控制文档必须包含的term数量

get /index1/_search
{
  "query":{
    "match": {
      "name": {
        "query": "chen jack",
        "minimum_should_match": "2"    //应该有2个term被匹配
      }
    }
  }
}

如果我们想保持查询条件分词后仍然保持顺序,那么可以使用match_phrase

get /index1/_search
{
  "query":{
    "match_phrase": {
      "name":"jack chen"  //文档里顺序必须紧邻一致才能被查询出结果
    }
  }
}

也可以使用slop参数控制单词间的间距

get /index1/_search
{
  "query":{
    "match_phrase": {
      "name":{
        "query": "jack chen",
        "slop": 1    //允许文档中jack chen中间隔一个单词,如 “jack aa chen”符合条件
      }
    }
  }
}