Full text search AND sorting in C#

1,319 views
Skip to first unread message

Thomas

unread,
Aug 24, 2015, 10:15:12 PM8/24/15
to mongodb-csharp
I'm trying to implement the text search in MongoDB, in C#.

The documentation doesn't cover anything about how to sort the text search results in C#.

I have a list of tags, separated by spaces, to match.
If I provide a string like "Tag1 Tag2", I would like the results to be provided in the following order:
   

 1. Anything that has BOTH 'Tag1' AND 'Tag2', followed by
 2. Anything that has only 'Tag1', followed by
 3. Anything that has only 'Tag2'

I have been trying to piece together some code:

    var F = Builders<MongoPost>.Filter.Text(Tags);
    var S = Builders<MongoPost>.Sort.MetaTextScore("textScore");
    return Mongo.Driver.Find(F).Sort(S).ToListAsync().Result;

But I get the following error:
 {"QueryFailure flag was true (response was { \"$err\" : \"Can't canonicalize query: BadValue must have $meta projection for all $meta sort keys\", \"code\" : 17287 })."}

No proper documentation for this error...

Then I found the following code on stackoverflow:

    var pipeline = new List<BsonDocument>
    {
        BsonSerializer.Deserialize<BsonDocument>("{ $match: { $text: { $search: \"" + Tags + "\" } } }"),
        BsonSerializer.Deserialize<BsonDocument>("{ $sort: { score: { $meta: \"textScore\" } } }")
    };

    var R = Mongo.Driver.AggregateAsync(new BsonDocumentStagePipelineDefinition<MongoPost, MongoPost>(pipeline)).Result;
    return R.ToListAsync().Result;

At least is runs without error, but I am trying to make the code in the style at the top, like you can do for the rest of the API, as I need to add more criteria to the search, etc

Is there any proper documentation I missed? If not, does anyone know how to implement this in the style at the top?

Thomas

unread,
Aug 24, 2015, 10:48:08 PM8/24/15
to mongodb-csharp


    var F = Builders<MongoPost>.Filter.Text(Tags);
    var P = Builders<MongoPost>.Projection.MetaTextScore("TextMatchScore");
    var S = Builders<MongoPost>.Sort.MetaTextScore("TextMatchScore");
    return Mongo.Driver.Find(F).Project<MongoPost>(P).Sort(S).ToListAsync().Result;

And my class <em>MongoPost</em> has the following field:

    [BsonIgnoreIfNull]
    public double? TextMatchScore { get; set; }
Reply all
Reply to author
Forward
0 new messages