继续跟中华石杉老师学习ES,第三篇
课程地址: https://www.roncoo.com/view/55
https://www.elastic.co/guide/en/elasticsearch/reference/6.4/query-dsl-terms-filter.html
6.4版本对应的 terms query
https://www.elastic.co/guide/en/elasticsearch/reference/6.4/query-dsl-terms-query.html
7.0 版本对应的 terms query
https://www.elastic.co/guide/en/elasticsearch/reference/7.0/query-dsl-terms-query.html
前面的实例中,我们都是使用的term,只能将一个字段,从一个value中取搜索
term: {"field": "value"}
比如
{
"term": {
"articcleID": "XHDK-A-1293-#fJ3"
}
}
terms 呢? terms可以实现将一个字段,从多个value中检索的效果
terms: {"field": ["value1", "value2"]}
类似于SQL中的in
select * from table where col in ("value1","value2"......)
为了演示terms, 我们再新增个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"]}}
GET /forum/_search
{
"query": {
"constant_score": {
"filter": {
"terms": {
"articleID": [
"KDKE-B-9947-#kL5",
"QQPX-R-3956-#aD8"
]
}
}
}
}
}
Terms Query写法(推荐)
GET /forum/_search
{
"query": {
"terms": {
"articleID": [
"KDKE-B-9947-#kL5",
"QQPX-R-3956-#aD8"
]
}
}
}
GET /forum/_search
{
"query": {
"constant_score": {
"filter": {
"terms": {
"tag": [
"java"
]
}
}
}
}
Terms Query写法(推荐)
GET /forum/_search
{
"query": {
"terms": {
"tag": [
"java"
]
}
}
}
上面的第二个例子中,搜索java ,可以看到返回了3条结果,其中
"tag": [
"java",
"elasticsearch"
]
"tag": [
"java",
"hadoop"
],
也被搜索出来了,如果仅仅是想搜索tag只包含java的帖子呢 ?
为了达到该效果,我们新增个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}}
GET /forum/_search
{
"query": {
"constant_score": {
"filter": {
"bool": {
"must": [
{
"term": {
"tag_cnt": 1
}
},
{
"terms":{
"tag":["java"]
}
}
]
}
}
}
}
}
Terms Query写法(推荐) ,_score 固定为1
GET /forum/_search
{
"query": {
"bool": {
"filter": [
{
"term": {
"tag_cnt": 1
}
},
{
"terms": {
"tag": [
"java"
]
}
}
]
}
}
}
计算相关度分数 _score 的写法
GET /forum/_search
{
"query": {
"bool": {
"must": [
{
"term": {
"tag_cnt": 1
}
},
{
"terms": {
"tag": [
"java"
]
}
}
]
}
}
}
总结一下: