Elasticsearch -查找具有分数的数组项



我需要返回一个包含尽可能多的用户提供的标签的帖子得分列表。标签以对象的形式存储在数组中,用户请求包含一个标签id数组(例如:["a", "c"])。单个文档看起来像这样:

{
id: 1,
meta: {
tags: [{id: "a", name: "Engine"}, {id: "b", name: "Street"}, {id: "c", name: "Sport"}]
}
}

遗憾的是,term查询返回的帖子几乎是随机顺序的,因为它们的得分都是1.0:

{
"query": {
"bool": {
"must": [
{
"terms": {
"meta.tags.id.keyword": [
"a", "c"
]
}
}
]
}
}
}

我认为如果所有的标签都在一个字符串中,那就很容易了,因为这将是正常的全文搜索,但是如何实现这样的对象数组呢?

下面是一个映射异常(由NEST客户端动态创建):

"mappings" : {
"properties" : {
"categories" : {
"properties" : {
"id" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"name" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
},
"description" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"id" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"inFavourite" : {
"type" : "long"
},
"likes" : {
"type" : "long"
},
"name" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"photoPath" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"meta" : {
"properties" : {
"tags" : {
"properties" : {
"id" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"name" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
}
},
}
},
"userId" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"viewCounter" : {
"type" : "long"
}
}
}
  • 你可能想提高不同的查询分数,比如问题Elasticsearch排序基于字符串出现在数组中的次数
  • 您还想更改条件的逻辑关系。Cond1或cond2或cond3 ->(cond1和;cond2) | cond3.
  • ,然后你可能想写自定义分数函数来计算,例如
{
"query": {
"function_score": {
"query": { "match_all": {} },
"boost": "5", 
"functions": [
{
"filter": { "match": { "test": "bar" } },
"random_score": {}, 
"weight": 23
},
{
"filter": { "match": { "test": "cat" } },
"weight": 42
}
],
"max_boost": 42,
"score_mode": "max",
"boost_mode": "multiply",
"min_score": 42
}
}
}

最新更新