2016-11-04 182 views
0

我在Mongodb中使用聚合方法對文本搜索。我已經嘗試過各種方式,仍然無法找到正確的方法來過濾我的結果。我已經設置了一個索引,並且只需$ text搜索就可以正常工作,並且只需查詢即可正常工作。Mongodb - 如何使用聚合文本搜索與查詢查詢

這裏是我的代碼做一個文本搜索:

Model.aggregate([ 
    { $match: { $text: { $search: searchValue } } }, 
    { $project: { displayTitle: 1, title: 1, body: 1, _type: 1, _id: 1, score: { $meta: "textScore" } } }, 
    { $match: { score: { $gt: 1.0 } } } 
], function (err, models) { 

}) 

不過,我希望能夠通過這個查詢進一步篩選模型:

Model.find({_parentIds: {$in: arrayOfIds}}) 

我本來以爲這會工作:

Model.aggregate([ 
    { $match: { $text: { $search: searchValue }, _parentIds: {$in: arrayOfIds} } }, 
    { $project: { displayTitle: 1, title: 1, body: 1, _type: 1, _id: 1, score: { $meta: "textScore" } } }, 
    { $match: { score: { $gt: 1.0 } } } 
]) 

但可悲的是它沒有。有沒有人試過這個或我錯過了什麼?

這裏有一個例子收集我通過搜索:

[{ 
    displayTitle: "first item", 
    title: "first_item", 
    _type: "item", 
    _parentIds: ["123", "234"] 
}, { 
    displayTitle: "second item", 
    title: "second_item", 
    _type: "item", 
    _parentIds: ["123", "234"] 
}, { 
    displayTitle: "third item", 
    title: "third_item", 
    _type: "item", 
    _parentIds: ["345", "456"] 
}] 

我現在的搜索將是這樣的:

searchValue = "item" 
arrayOfIds = ["345"]; 

和將本文件期望只回:

{ 
    displayTitle: "third item", 
    title: "third_item", 
    _type: "item", 
    _parentIds: ["345", "456"] 
} 

謝謝!

+0

能否請你添加樣本文檔和預期產出? – Veeram

+0

@Veeram - 我添加了一個樣本集合和預期的輸出 – darylhedley

回答

1

文字評分爲0.75。所以將匹配過濾器改爲大於0.5的作品。

修改投影以排除身體_id幷包含父母ID。

使用此查詢創建索引。

db.textcol.createIndex({ displayTitle: "text" }) 

運行此查詢。

db.textcol.aggregate([ 
    { $match: { $text: { $search: "item" }, _parentIds: {$in: ["345"]} }} , 
    { $project: { displayTitle: 1, title: 1, _type: 1, _id: 0, _parentIds :1, score: { $meta: "textScore" } }}, 
     { $match: { score: { $gt: 0.5 } } } 
]) 

輸出:

{ 
    "displayTitle": "third item", 
    "title": "third_item", 
    "_type": "item", 
    "_parentIds": ["345", "456"], 
    "score": 0.75 
} 
+0

謝謝!這救了我!所以,我應該更清楚一些的實際問題是它返回了我不想要的結果(所以_parentIds數組中沒有_parentId的模型)。上面的解決方案解決了這個問題,主要原因是$ project中的_parentIds:1和_id:0,並且得分的$匹配太高 - 不知道我怎麼沒看到...... – darylhedley