针对两个值(术语和范围)的弹性搜索查询?



我正在尝试进行查询,其中我想要基于两个值的文档 - 名称(字符串(和百分比(数字(。 例如 - 我希望那些具有"audience.location.countries.name"="美国"和"受众.位置.国家.百分比"的文档> 60。所以我想要一个具有对象{"名称":"US","百分比":"65"}的文档 在这里,"audience.location.countries"是一个具有两个属性的对象数组 - {"name","percent"}。 下面是一个示例文档:

"location": {
"countries": [
{
"name": "CA",
"percentage": 4
},
{
"name": "GB",
"percentage": 5
},
{
"name": "JP",
"percentage": 8
},
{
"name": "US",
"percentage": 60
}
]}  

这是我尝试过的查询,但它抛出了一个错误:"[和]查询格式不正确,查询名称后没有start_object">

GET opensponsorship/_search
{
"query": {
"bool": {
"filter": [
{
"term": {
"isPublic": true
}
},
{
"term": {
"isDeleted": false
}
},
{
"and":[
{
"range": {
"audience.location.countries.name": "US"
}
},
{
"term":{
"audience.location.countries.percentage": {"gt": 59}
}
}
]
}
]
}
},
"size": "60",
"from": 0,
"sort": [
{
"followers": {
"order": "desc"
}
}
]
}

我是弹性搜索的新手,知识非常有限。有人可以帮忙吗?

据我所知,查询在几个帐户上是"损坏的":

  1. 您使用已弃用的and查询(顺便说一句,您使用的是哪个 ES 版本?
  2. namepercentage字段上的rangeterm筛选器是混合
  3. 字段audience.location.countries应为"嵌套对象">

以下是解决问题 1 和 2 的查询。然后我将解释问题 3:

GET opensponsorship/_search
{
"query": {
"bool": {
"filter": [
{
"term": {
"isPublic": true
}
},
{
"term": {
"isDeleted": false
}
},
{
"term": {
"audience.location.countries.name": "US"
}
},
{
"range": {
"audience.location.countries.percentage": {
"gt": 59
}
}
}
]
}
},
"size": "60",
"from": 0,
"sort": [
{
"followers": {
"order": "desc"
}
}
]
}

关于问题 3,我建议您阅读 elasticsearch 中的嵌套字段。 简而言之,如果audience.location.countries不是嵌套对象,由于 Elastic 如何"展平"对象,您将得到"误报"结果。 要解决此问题,您需要 1( 在映射中audience.location.countries嵌套对象类型,以及 2( 按以下方式使用嵌套查询包装contries术语筛选器:

GET opensponsorship/_search
{
"query": {
"bool": {
"filter": [
{
"term": {
"isPublic": true
}
},
{
"term": {
"isDeleted": false
}
},
{
"nested": {
"path": "audience.location.countries",
"query": {
"bool": {
"filter": [
{
"term": {
"audience.location.countries.name": "US"
}
},
{
"range": {
"audience.location.countries.percentage": {
"gt": 59
}
}
}
]
}
}
}
}
]
}
},
"size": "60",
"from": 0,
"sort": [
{
"followers": {
"order": "desc"
}
}
]
}

希望这有帮助。祝你好运!

最新更新