问题描述
我有这个用户集合:
{
"_id" : ObjectId("501faa18a34feb05890004f2"),
"username" : "joanarocha",
}
{
"_id" : ObjectId("501faa19a34feb05890005d3"),
"username" : "cristianarodrigues",
}
{
"_id" : ObjectId("501faa19a34feb05890006d8"),
"username" : "anarocha",
}
当我查询以下内容时: db.users.find({'username': /anaro/i})
结果以自然顺序(插入顺序)排序.
When I query this: db.users.find({'username': /anaro/i})
results are sorted in natural order (insertion order).
我想按相似性搜索词顺序对其进行排序.在这种情况下,结果应按以下顺序返回:
I would like to sort them in a similarity search-term order. In this case results should return by this order:
{
"_id" : ObjectId("501faa19a34feb05890006d8"),
"username" : "anarocha",
}
{
"_id" : ObjectId("501faa18a34feb05890004f2"),
"username" : "joanarocha",
}
{
"_id" : ObjectId("501faa19a34feb05890005d3"),
"username" : "cristianarodrigues",
}
推荐答案
不幸的是,默认情况下,MongoDB不支持全文搜索排名.
Unfortunately, MongoDB doesn't support full text search ranking by default.
首先,您将需要一种算法来计算字符串之间的相似度.请参阅以下链接:
First of all, you will need a algorithm to calculate the similarity between strings. See following links:
然后,您需要使用算法将 javascript函数编写为一个比较两个字符串在查询中传递它.请参阅以下链接以了解如何实现:
Then you need to write a javascript function using the algorithm to compare two strings to pass it in your query. See the following link to see how to achieve that:
这篇关于按搜索字词相似度对结果进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!