如果可以重新创建索引,请为此目的使用自定义 _all 字段。索引时间优化将为您提供比搜索时间优化更好的性能。因此,您可以创建如下映射:
PUT /my_index/_mapping/my_mapping
{
"_all": {"enabled": false},
"properties": {
"custom_all": {
"type": "string"
},
"username": {
"copy_to": "custom_all",
"type": "string"
},
"city": {
"copy_to": "custom_all",
"type": "string"
},
"country": {
"copy_to": "custom_all",
"type": "string"
}
}
无论您希望搜索什么字段,都可以使用 copy_to 参数将它们包含在 custom_all 字段中。现在您可以对 custom_all 字段执行搜索。
GET /my_index/my_mapping/_search
{
"query": {
"match": {
"custom_all": "text to match"
}
}
}
如果你想给用户名匹配的那些记录更高的优先级,你可以使用这样的 bool 查询:
GET /my_index/my_mapping/_search
{
"query": {
"bool": {
"must": {
"match": {"custom_all": "text to match"}
},
"should": [
{ "match": { "username": "text to match" } }
]
}
}
}
must 子句确保查询匹配 custom_all 字段。should 子句确定文档的分数。如果 should 子句匹配,则得分会更高。同样,在数组中添加更多的 should 子句将包括不同的评分标准。您还可以在 should 子句中添加 boost 参数,以确定哪个字段对总分的贡献程度。希望这可以帮助。