从多个字段 Elastic Search 的集合中随机搜索自由文本

Random free text search from a collection from multiple fields Elastic Search

我们正在使用 Elastic Search,MongoDB,mongoosastic

假设

User:{
  username:String,
  city : String,
  country:String 
   etc 
}

这种类型的文档存储在 Elastic Search 中,现在如果用户搜索 abhay sikandrabad,那么它会首先尝试同时查找 abhay 和 sikandrabad。 abhay,sikandrabad 可能出现在用户名、城市、国家/地区中的任何一个中。所以基本上它从每个字段中搜索,如果不匹配,则尝试匹配 abhay,如果未找到带有 abhay 的数据,则尝试查找 sikandrabad

Elastic Search 中是否已经实现了此类功能,或者我必须为此编写代码?

我认为最接近您描述的查询是 multi_match querybest_fields 模式。即使有所有单词匹配的记录,它仍然会return条只有一个单词匹配的记录,但是所有单词的记录会出现在列表的顶部。

如果可以重新创建索引,则为此目的使用自定义 _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 子句将包括不同的评分标准。您还可以将 boost 参数添加到 should 子句以确定哪个字段对总分的贡献有多大。希望这有帮助。

如果您想在多个字段中搜索一个值,请增加 should 方法的数量并传递更多字段键。如果您想优先考虑字段,请将 .should 替换为 .must

.setQuery(QueryBuilders.boolQuery()
.should(QueryBuilders.matchQuery(field1_key, value))
.should(QueryBuilders.matchQuery(field 2_key, value)) )