搜索條件的mongodb map reduce (mongodb map reduce for search criteria)


問題描述

搜索條件的mongodb map reduce (mongodb map reduce for search criteria)

我有一個包含名為 searchTerms 的字段的 mongo 文檔。這是一個包含單詞的數組 例如 ["term1","term2", "term3","term4"]

我想編寫一個按相關性返回文檔的函數。這意味著在 searchCriteria 中搜索詞最多的文檔首先緊隨其後,其次是數量最多的詞等。

示例:

文檔:

   {"_id":"1", "searchTerms":["a","b","c","d"]}
   {"_id":"2", "searchTerms":["a","b","x","q"]}
   {"_id":"3", "searchTerms":["a","e","x","n"]}
   {"_id":"4", "searchTerms":["e","f","g","z"]}

For搜索條件:["a","b","c"] 結果應該是:

{"_id":"1", "searchTerms":["a","b","c","d"]}
{"_id":"2", "searchTerms":["a","b","x","q"]}
{"_id":"3", "searchTerms":["a","e","x","n"]}

我已經編寫了一個函數來執行此操作,但是它非常複雜並且我認為效率低下。我正在閱讀有關 map reduce 的內容,並想知道它在這種情況下是否有幫助?我絞盡腦汁想辦法解決這個問題。我不確定它是否可以?如果是,有人可以告訴我它是如何工作的嗎?


參考解法

方法 1:

A simple set operator will suffice. Use $setIntersection for comparsion with input array and $project $size of intersected array. $sort on size descending and project the final response.

aggregate([{
    "$project": {
        "_id":0,
        "fields" : "$$ROOT",
        "matches": {
            "$size": {
                "$setIntersection": [
                    "$searchTerms", ["a", "b"]
                ]
            }
        }
    }
}, {
    "$sort": {
        "matches": ‑1
    }
}])

(by johhny Bs7vr)

參考文件

  1. mongodb map reduce for search criteria (CC BY‑SA 2.5/3.0/4.0)

#mongoDB #algorithm #mapreduce






相關問題

將 (.net) BsonDocument 字符串轉換為 (java) DBObject (Converting (.net) BsonDocument string into a (java) DBObject)

Mongo 客戶端出錯 (Error with Mongo Client)

對列表進行排序並在 mongodb 中插入一個新列 (Sort the list and insert a new column in mongodb)

無法導入示例數據集(系統找不到指定文件) (Cannot import example dataset (the system cannot find the specified file))

mongodb c#更新嵌入文檔 (mongodb c# update embedded document)

查詢嵌入列表中的數組 (Querying for array in embedded list)

搜索條件的mongodb map reduce (mongodb map reduce for search criteria)

org.bson.codecs.configuration.CodecConfigurationException:找不到類 [Ljava.lang.String; 的編解碼器; (org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class [Ljava.lang.String;)

在碼頭上部署 gwt Web 應用程序 (deploying gwt web application on jetty)

MongoMetaRecord MegaProtoUser 登錄時密碼未散列 (MongoMetaRecord MegaProtoUser Password not hashed when signing in)

將 mongo shell 連接到受限的 MongoDB Atlas 數據庫? (Connect mongo shell to restricted MongoDB Atlas Database?)

用於 $or 和 $and 場景的 $elemMatch 數組 (Arrays working $elemMatch for $or and $and scenarios)







留言討論