创建索引
db.MyCollection.createIndex({'$**': 'text'}, {name: 'FullTextIndex'})
搜索匹配
db.MyCollection.find({$text: {$search: 'myWord'}}).count()
结果为 1。对于具有“myWord is here”值的字段
如果我按以下方式定期搜索所选字段,我会得到两条记录,一条记录有 Name = "myWord is here",第二条记录有 "myWord"在详细信息中归档为“something here and myWord is here”
db.getCollection('MyCollection').find({
"$or":[{"Name":/myWord/i}, {"Details":/myWord/i}]
}).sort({"Name": 1})
如何重新创建索引,以便它在所有字段中搜索为 SQL,其中任何字段如 %searchText%
最后,我如何在 C# 驱动程序中编写这个搜索查询
更新:
我进一步调查了它。它正在查找所有搜索关键字带有前缀和后缀空格的结果,但不是单词中字符串的一部分。
例如,它返回值“Hello myWord is here”的记录,但不返回“HellomyWord”
但是根据这个文档,它必须支持通配符搜索。 https://docs.mongodb.com/v3.0/reference/operator/query/text/
最佳答案
由于我没有找到对使用 Mongo 进行通配符搜索/全文搜索有很大帮助的方法,所以我想出了一个解决方法来满足我的要求。
foreach (var doc in batch)
{
if (custDictionary.ContainsKey(projectId))
{
string concatenatedCustomFields = custFieldsList.Aggregate(string.Empty,
(current, custField) =>
current +
(ds.Tables[0].Columns.Contains(custField)
? (ds.Tables[0].Rows[i][custField].GetType().Name == typeof(DBNull).Name
? string.Empty
: ((string) ds.Tables[0].Rows[i][custField]).StripHtml())
: string.Empty));
doc.Add("CustomFieldsConcatenated", concatenatedCustomFields);
}
i++;
}
我读取每组文档的自定义字段列表,然后创建一个串联的 Mongo 字段,然后对该字段使用正则表达式查询。
然后为了提高查询的性能添加了以下索引
_mongoConnect.Database?.GetCollection<BsonDocument>("MyCollectionName")
.Indexes.CreateOneAsync(new BsonDocument("CustomFieldsConcatenated", "hashed"), new CreateIndexOptions { Name = "CollectionName_FieldName_Index" });
关于c# - MongoDB全文搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37283589/