问题
Using v1.9.0 of the C# driver (latest at time of writing) with MongoDB 2.6.0
What is the best way currently to create a text index on a collection, via the C# driver?
From what I could tell, it's not possible via MongoCollection.CreateIndex
? So currently creating it using MongoDatabase.Eval like so:
Database.Eval(new EvalArgs { Code = "function(){db.dummycollection.ensureIndex({\"$**\" : \"text\"},{name:\"TextIndex\"});}"
Am I missing something / is there a better way?
回答1:
This should work:
collection.EnsureIndex(IndexKeys.Text("a", "b").Ascending("c"), IndexOptions.SetTextLanguageOverride("idioma").SetName("custom").SetTextDefaultLanguage("spanish"));
https://jira.mongodb.org/browse/CSHARP-874
https://github.com/mongodb/mongo-csharp-driver/commit/1e7db3bedb3bee1b0ccecdb5f8ff39854526213a
回答2:
Just verified that the following works with the 1.9.0 C# driver and MongoDB 2.6.0-rc2:
MongoCollection.CreateIndex(new IndexKeysDocument("Markdown", "text"));
(this also works with older drivers)
EDIT
djch's answer shows the better way to do it using the 1.9 driver because it can also be used stronly-typed, e.g.:
MongoCollection.CreateIndex(IndexKeys<MyClass>.Text(p => p.Markdown));
回答3:
the easiest way to create indexes in c# is by using the driver wrapper library MongoDB.Entities. here's an example of creating a text index:
DB.Index<Author>()
.Key(a => a.Name, Type.Text)
.Key(a => a.Surname, Type.Text)
.Create();
and to do a full-text search, you simply do:
DB.SearchText<Author>("search term");
it doesn't get any simpler than that :-)
来源:https://stackoverflow.com/questions/23383322/best-way-to-create-a-text-index-on-a-mongodb-collection-via-c-sharp-driver