Elasticsearch 2.4搜索过滤器:将术语与正则表达式混合

时间:2019-06-10 22:24:35

标签: elasticsearch

我想进行搜索以混合术语和正则表达式。 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
        }
    }
}

}

1 个答案:

答案 0 :(得分:2)

我认为您需要使用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"
           }
          }
         ]
        }
       }