MongoDB全文搜索

HaB*_*aBo 7 c# mongodb

创建索引

db.MyCollection.createIndex({'$**': 'text'}, {name: 'FullTextIndex'})
Run Code Online (Sandbox Code Playgroud)

搜索匹配

db.MyCollection.find({$text: {$search: 'myWord'}}).count()
Run Code Online (Sandbox Code Playgroud)

结果为1.对于具有" myWord is here " 值的字段

如果我定期搜索所选字段如下,我得到两条记录,一条记录名称=" myWord就在这里 ",第二条记录中的" myWord "在详细信息中归档为" 这里的东西,myWord就在这里 "

db.getCollection('MyCollection').find({  
     "$or":[{"Name":/myWord/i}, {"Details":/myWord/i}]
    }).sort({"Name": 1})
Run Code Online (Sandbox Code Playgroud)

如何重新创建索引,以便在所有字段中搜索SQL,其中包含%searchText%等字段

最后,我如何在C#Driver中编写此搜索查询

更新:


我进一步调查了它.它找到所有带有前缀和后缀空格的搜索键的结果,但不是单词中字符串的一部分.

示例它返回值为" Hello myWord is here "的记录,但不返回" HellomyWord "

但是根据这个文档,它必须支持通配符搜索.https://docs.mongodb.com/v3.0/reference/operator/query/text/

HaB*_*aBo 3

由于我还没有找到使用 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++;
 }
Run Code Online (Sandbox Code Playgroud)

我读取每组文档的自定义字段列表,然后创建一个串联的 Mongo 字段,然后对该字段使用正则表达式查询。

然后为了提​​高查询的性能添加以下索引

  _mongoConnect.Database?.GetCollection<BsonDocument>("MyCollectionName")
                .Indexes.CreateOneAsync(new BsonDocument("CustomFieldsConcatenated", "hashed"), new CreateIndexOptions { Name = "CollectionName_FieldName_Index" });
Run Code Online (Sandbox Code Playgroud)