How can I sort mongodb regex search query results based on regex match count

拜拜、爱过 提交于 2020-01-04 16:25:14

问题


I can't figure out how to sort query results based on the "best" match.

Here's a simple example, I have a "zone" collection containing a list of city/zipcode couples.

If I search several words through the regex using the "and" keyword like that :

"db.zones.find({$or : [ {ville: /ROQUE/}, {ville: /ANTHERON/}] })"

Results won't be ordered by "best match".

What other solutions do I have for that ?


回答1:


You could try to use http://docs.mongodb.org/manual/reference/operator/query/text/#match-any-of-the-search-terms

db.zones.ensureIndex( {  'ville' : 'text' } ,{ score: {$meta:'textScore'}}) 

db.zones.find(
   { $text: { $search: "ROQUE ANTHERON"}},
   { score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )

Result:

{
    "_id" : ObjectId("547c2473371ea419f07b954c"),
    "ville" : "ANTHERON",
    "score" : 1.1
}

{
    "_id" : ObjectId("547c246f371ea419f07b954b"),
    "ville" : "ROQUE",
    "score" : 1
}

From documentation

If the search string is a space-delimited string, $text operator performs a logical OR search on each term and returns documents that contains any of the terms.

You have to use mongodb 2.6




回答2:


I ended up using ElasticSearch search engine do this query :

@zones = Zone.es.search(
    body: {
      query: {
        bool: {
          should: [
            {match: {city: search}},
            {match: {zipcode: search.to_i}}
          ]
        }
      },
      size: limit
    })

Where search is a search param sent by view.

ElasticSearch with Selectize plugin



来源:https://stackoverflow.com/questions/27224225/how-can-i-sort-mongodb-regex-search-query-results-based-on-regex-match-count

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