Sort results by search term similarity

爱⌒轻易说出口 提交于 2019-12-10 15:32:58

问题


I have this users collection:

{
    "_id" : ObjectId("501faa18a34feb05890004f2"),
    "username" : "joanarocha",
}
{
    "_id" : ObjectId("501faa19a34feb05890005d3"),
    "username" : "cristianarodrigues",
}
{
    "_id" : ObjectId("501faa19a34feb05890006d8"),
    "username" : "anarocha",
}

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",
}

回答1:


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:

String similarity algorithims?

String similarity -> Levenshtein distance

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:

Mongo complex sorting?



来源:https://stackoverflow.com/questions/12005490/sort-results-by-search-term-similarity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!