1

我们正在使用 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 中实现,或者我必须为此编写代码?

4

3 回答 3

2

如果可以重新创建索引,请为此目的使用自定义 _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 参数,以确定哪个字段对总分的贡献程度。希望这可以帮助。

于 2015-09-12T19:16:26.307 回答
0

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

于 2015-09-11T13:27:53.677 回答
-1

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

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

于 2016-01-20T10:27:11.483 回答