1、搜索articleID为KDKE-B-9947-#kL5或QQPX-R-3956-#aD8的帖子
数据准备,新增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"]} }
SQL:
select * form tb1 where col in (value1,value2)
ES:
GET /forum/article/_search
{
"query": {
"constant_score": {
"filter": {
"terms": {
"articleID.keyword": [
"KDKE-B-9947-#kL5",
"QQPX-R-3956-#aD8"
]
}
}
}
}
}
2、搜索tag中包含java的帖子
SQL:
select * from tb1 where tag like '%java%'
ES:
GET /forum/article/_search
{
"query": {
"constant_score": {
"filter": {
"terms": {
"tag" : ["java"]
}
}
}
}
}
会返回三条,["java", "hadoop"],["java"],["java", "elasticsearch"]
3、若仅仅想搜索只包含java的帖子怎么办?(就是说不想要["java", "hadoop"],["java", "elasticsearch"])
可以新增字段,比如新增tag_cnt代表个数
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} }
SQL:
select * from tb1 where tag_cnt = 1 and tag like '%java%'
ES:
GET /forum/article/_search
{
"query": {
"constant_score": {
"filter": {
"bool": {
"must" : [
{"term" : {"tag_cnt" : 1}},
{"terms" : {"tag" : ["java"]}}
]
}
}
}
}
}
只会返回tag为["java"]的这一条结果
4、梳理学习到的知识点
(1)terms多值搜索
(2)优化terms多值搜索的结果
(3)相当于SQL中的in语句
若有兴趣,欢迎来加入群,【Java初学者学习交流群】:458430385,此群有Java开发人员、UI设计人员和前端工程师。有问必答,共同探讨学习,一起进步!
欢迎关注我的微信公众号【Java码农社区】,会定时推送各种干货:
qrcode_for_gh_577b64e73701_258.jpg
网友评论