5.terms搜索多个值以及多值搜索结果优化

主要知识点

terms搜索多个值,并和term的比较

   

一、termterms

terms是在这个字段中搜索多个值,相当于sql中的in语法

select * from tbl where col in ("value1", "value2")

  • term: {"field": "value"}
  • terms: {"field": ["value1", "value2"]}

   

terms搜索

1、为帖子数据增加tag字段

   

POST /forum/article/_bulk

{ "update": { "_id": "1"} }

{ "doc" : {"tag" : ["java", "hadoop"]} }

{ "update": { "_id": "2"} }

{ "doc" : {"tag" : ["java"]} }

{ "update": { "_id": "3"} }

{ "doc" : {"tag" : ["hadoop"]} }

{ "update": { "_id": "4"} }

{ "doc" : {"tag" : ["java", "elasticsearch"]} }

   

2、搜索articleIDKDKE-B-9947-#kL5QQPX-R-3956-#aD8的帖子

GET /forum/article/_search

{

"query": {

"constant_score": {

"filter": {

"terms": {

"articleID": [

"KDKE-B-9947-#kL5",

"QQPX-R-3956-#aD8"

]

}

}

}

}

}

3、搜索tag中包含java的帖子

GET /forum/article/_search

{

"query" : {

"constant_score" : {

"filter" : {

"terms" : {

"tag" : ["java"]

}

}

}

}

}

   

三、优化搜索结果,仅仅搜索tag只包含java的帖子

1、先向index插入一条数据,显示tags中字段的个数

POST /forum/article/_bulk

{ "update": { "_id": "1"} }

{ "doc" : {"tag_cnt" : 2} }

{ "update": { "_id": "2"} }

{ "doc" : {"tag_cnt" : 1} }

{ "update": { "_id": "3"} }

{ "doc" : {"tag_cnt" : 1} }

{ "update": { "_id": "4"} }

{ "doc" : {"tag_cnt" : 2} }

   

2、执行搜索语句

GET /forum/article/_search

{

"query": {

"constant_score": {

"filter": {

"bool": {

"must": [

{

"term": {

"tag_cnt": 1

}

},

{

"terms": {

"tag": ["java"]

}

}

]

}

}

}

}

}

   

["java", "hadoop", "elasticsearch"]

   

三、总结

1terms多值搜索用列表的形式表示

2)优化terms多值搜索的结果,获取我们指定的特定结果集

3terms相当于SQL中的in语句

原文地址:https://www.cnblogs.com/liuqianli/p/8482958.html