更加重视一个领域的存在

Giving more weight to existence of a field

我正在尝试学习和编写弹性搜索查询。我意识到有一个 "exists" 字段表明 returns 指定字段的文档是否存在。学习我写了一个简单的查询,我想了解更多并尝试使用查询结构。

我有一个查询,它只检查至少一个指定字段是否存在。但是,我想给一个领域更多的权重。这是我的查询:

"query": {
"bool": {
  "minimum_should_match" : 1,
  "should": [
    {
      "exists": {
        "field": "geo"
      }
    },
    {
      "exists": {
        "field": "location"
      }
    }
  ]
   "size": 100
}

我想先获取所有有geo字段的文档(比如有30个文档包含location字段),剩下的70个(size - documents exists geo field)将包含location字段的文档(other应该)。因此,对于我的情况,位置字段权重的存在小于地理存在。

我为此尝试了 boost,但它对我的情况不起作用;

"query": {
"bool": {
  "minimum_should_match" : 1,
  "should": [
    {
      "exists": {
        "field": "geo",
        "boost": 5 
      }
    },
    {
      "exists": {
        "field": "location"
      }
    }
  ]
   "size": 100
}

当我将 minimum_should_match 更改为 2 时,它只有 returns 个存在地理字段的文档。

您不应在这种情况下使用 boost。改为使用排序:

"query": {
  "bool": {
    "minimum_should_match" : 1,
    "should": [
      {
        "exists": {
          "field": "geo"
        }
      },
      {
        "exists": {
          "field": "location"
        }
      }
    ]
  "size": 100
  }
},
"sort" : [
  { "geo" : {"order" : "asc"}},
  { "location" : {"order" : "asc"}}
]

这样您将对结果进行排序(首先是带有地理字段的文档,然后是带有位置字段的文档)

你应该试试这个查询

{
  "query": {
    "function_score": {
      "functions": [
        {
          "filter": {
            "exists": {
              "field": "geo"
            }
          },
          "weight": 2
        },
        {
          "filter": {
            "exists": {
              "field": "location"
            }
          },
          "weight": 1
        }
      ]
    }
  },
  "from": 0,
  "_source": [
    "geo", "location"
  ],
  "size": 100
}

结果如下;

 {
    "_index": "mentions",
    "_type": "post",
    "_id": "1",
    "_score": 2,
    "_source": {
      "geo": {
        "lon": XXX,
        "lat": XXX
      },
      "location": "California, USA"
    }
  },

{
    "_index": "mentions",
    "_type": "post",
    "_id": "2",
    "_score": 1,
    "_source": {
      "location": "Berlin, Germany"
    }
  }

第一个的功能得分是 2,因为它有地理字段,但第二个没有。