我正在尝试对集合进行文本查询并按文本匹配顺序检索结果。The docs http://docs.mongodb.org/manual/reference/operator/query/text/#text-search-with-additional-query-and-sort-expressions很好地解释了如何在 shell 中执行此操作:
db.articles.find(
{ status: "A", $text: { $search: "coffee cake" } },
{ score: { $meta: "textScore" } }
).sort( { date: 1, score: { $meta: "textScore" } } )
但它需要额外的投影score
字段从查找到排序。
在 C# 中,我有一个如下所示的函数:
public IEnumerable<T> TextSearch<T>(MongoCollection<T> coll, string text) {
var cursor = coll.Find(Query.Text(text))
.SetSortOrder(SortBy<T>.MetaTextScore(???));
foreach(var t in cursor) {
// strip projected score from value
yield return t;
}
}
但我缺少如何将“textScore”值投影到我的结果中,以便我可以指定列 http://api.mongodb.org/csharp/current/?topic=html/4e4f953d-8756-5f12-e83a-fe7022adb420.htm to MetaTextScore
in SetSortOrder
.
我通过反复试验才得以实现这一目标。诀窍是您的数据对象需要有一个字段来保存MetaTextScore
价值。所以给定接口:
interface ITextSearchSortable {
double? TextMatchScore { get; set; }
}
最终函数如下所示:
public IEnumerable<T> TextSearch<T>(MongoCollection<T> coll, string text) where T:ITextSearchSortable {
var cursor = coll.Find(Query.Text(text))
.SetFields(Fields<T>.MetaTextScore(t => t.TextMatchScore))
.SetSortOrder(SortBy<T>MetaTextScore(t => t.TextMatchScore));
foreach(var t in cursor) {
// prevent saving the value back into the database
t.TextMatchScore = null;
yield return t;
}
}
值得注意的是TextMatchScore
不能有一个[BsonIgnore]
装饰,否则会有异常。然而,它可以有一个[BsonIgnoreIfNull]
装饰。因此,通过在生成数据对象之前清理数据对象的值,可以将数据对象保存回集合中,而无需放入垃圾值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)