首页 > 解决方案 > Elasticsearch 2.4 搜索过滤器:将术语与正则表达式混合

问题描述

我想进行搜索以混合术语和正则表达式。book_author 是一个术语搜索,我只想要一个特定的作者。对于 book_name,我想进行通配符搜索以支持我的 ui 上的提前输入功能。但是我让所有的书都以“我喜欢”开头,忽略了术语搜索。是否可以将术语与正则表达式搜索混合使用?我究竟做错了什么?

{
"size": 0,
"query": {
    "constant_score": {
        "filter": [{
                "term": {
                    "book_author": "mike jones"
                }
            }, {
                "regexp": {
                    "book_name": "I like.*"
                }
            }
        ]
    }
},
"aggs": {
    "values": {
        "terms": {
            "field": "book_name",
            "size": 0
        }
    }
}

}

标签: elasticsearch

解决方案


我认为您需要使用must,因为您想要匹配两个键的文档。例如:

我创建了这个mappingdocuments并向您展示如何仅提取满足与您用于搜索的两个键匹配的文档。

   PUT so_test7
   {
     "mappings":{
       "_doc": {
          "properties":{
             "book_author":{"type": "keyword"},
             "book_name": {"type":"text"}
           }
         }
       }
    }

样本文件

  POST /so_test7/_doc/1
  {
    "book_author": "mike jones",
    "book_name": "I like this"
  }

 POST /so_test7/_doc/2
 {
   "book_author": "some random",
   "book_name": "I like that"
 }

 POST /so_test7/_doc/3
 {
   "book_author": "new one",
   "book_name": "nope"
 }

 POST /so_test7/_doc/4
 {
   "book_author": "mike jones",
   "book_name": "not matching"
 }

这是我的查询

  GET /so_test7/_search
    { 
      "query":{
        "bool":{
          "must":[{
              "match":{"book_author":"mike jones"}
              },
              {
               "match":{"book_name":"I like.*"}
              }
             ]
          }
       }
     }

这是回应

 {
   "took" : 2,
   "timed_out" : false,
   "_shards" : {
   "total" : 5,
   "successful" : 5,
    "skipped" : 0,
    "failed" : 0
 },
 "hits" : {
    "total" : 1,
      "max_score" : 0.8630463,
        "hits" : [
            {
             "_index" : "so_test7",
             "_type" : "_doc",
             "_id" : "1",
             "_score" : 0.8630463,
             "_source" : {
             "book_author" : "mike jones",
             "book_name" : "I like this"
           }
          }
         ]
        }
       }

推荐阅读