使用C#驱动程序从MongoDB集合上的文本查询检索相关性排序结果 [英] Retrieve Relevance Ordered Result from Text Query on MongoDB Collection using the C# Driver
问题描述
我正在尝试对集合进行文本查询,并以文本匹配顺序检索结果. 文档很好地解释了如何在shell中执行此操作:
I am attempting to text query a collection and retrieve the results in the text match order. The docs explain pretty well how to do this in the shell:
db.articles.find(
{ status: "A", $text: { $search: "coffee cake" } },
{ score: { $meta: "textScore" } }
).sort( { date: 1, score: { $meta: "textScore" } } )
,但它需要将查找中的其他score
字段投影到排序中.
but it requires the projection of the additional score
field from the find into the sort.
在C#中,我有一个看起来像这样的函数:
In C#, I have a function that looks like this:
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"值投影到我的结果中,这样我就可以
but I am missing how to project the "textScore" value into my results, so that I can specify the column to MetaTextScore
in SetSortOrder
.
推荐答案
我能够通过反复试验来解决这个问题.诀窍是您的数据对象已经需要在其上具有一个字段,该字段将保存MetaTextScore
值.因此,给定接口:
I was able to get this working through trial and error. The trick is that your data object needs to have a field on it already that will hold the MetaTextScore
value. So given the interface:
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]
装饰.因此,通过在产生数据对象之前清除该数据对象的值,可以将该数据对象保存回集合中,而无需放入垃圾值.
It's worth noting that TextMatchScore
can't have a [BsonIgnore]
decoration, or there will be an exception. However, it can have a [BsonIgnoreIfNull]
decoration. So by scrubbing the value off the data object before yielding it, the data object can be saved back into the collection without putting in a garbage value.
这篇关于使用C#驱动程序从MongoDB集合上的文本查询检索相关性排序结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!