在 .net 中 mongodb 中进行全文搜索

Full text search in mongodb in .net

我必须在所有文档中搜索内容,特别是 .net mvc 中 mongodb 的集合。我试过 mongodb shell 像这里一样成功创建索引。

db.collection_name.createIndex( { subject: "text" } )

db.collection_name.find( { $text: { $search: "search_word" } } )

它工作正常。但是当我把它放在 .net 中时,它给了我错误。我用谷歌搜索并得到了以下索引解决方案。

 collection.EnsureIndex(new IndexKeysBuilder().Ascending("subject"));

现在我如何 运行 这个查询 db.collection_name.find( { $text: { $search: "coffee" } } ) .

我正在 .net 中按以下方式尝试。

collection.CreateIndex("subject":"text");

var query = collection.Find({ $text: { $search: "coffe" }}); 

但我在第一行收到错误 "represents text as series of unicode ....syntax error "

第二行错误"There is no argument given that corresponds to required formal parameters " 和"unexpected character $ ".

如有任何建议,我们将不胜感激。

我可以用这个命令创建文本索引:

collection.Indexes.CreateOne(Builders<searchFileByAuthor>.IndexKeys.Text(x=>x.subject));

而且我可以这样查询索引:

collection.Find(Builders<searchFileByAuthor>.Filter.Text("coffe")).ToList();

searchFileByAuthor 只是我的假 class 主题字段:

public class searchFileByAuthor
{
    public int Id { get; set; } 
    public string subject { get; set; } 
}
public List<T> FindSearch<T>(string collectionName, string searchWord) {
    IMongoQuery query = Query.Text(searchWord);
    List<T> find = getCollection<T>(collectionName).Find(query).ToList();
    return find;
}

Maksim Simkin 的回答是正确的,尽管它已经过时了。 更新后的版本为:

collection.Indexes.CreateOne(new CreateIndexModel<YourClass>(Builders<YourClass>.IndexKeys.Text(x => x.something)));

或者,如果您想使用 通配符索引(对整个文档进行索引),您可以这样做:

collection.Indexes.CreateOne(new CreateIndexModel<YourClass>(Builders<YourClass>.IndexKeys.Text("$**")));

或者您可能 want/have 出于某种原因比这样做更多的索引:

var indexWildcardTextSearch = new CreateIndexModel<YourClass>(Builders<YourClass>.IndexKeys.Text("$**"));

List<CreateIndexModel<YourClass>> indexes = new List<CreateIndexModel<YourClass>>();
indexes.Add(indexWildcardTextSearch);

collection.Indexes.CreateMany(indexes);

再去查询,还是一样:

collection.Find(Builders<YourClass>.Filter.Text("something")).ToList();