【问题标题】:MongoDb combine Text Search with other queries (using $or)MongoDb 将文本搜索与其他查询相结合(使用 $or)
【发布时间】:2015-09-09 19:32:00
【问题描述】:

使用 Mongo C# 驱动程序 (1.10) 我正在尝试编写一个将文本搜索与其他过滤器相结合的查询。注意:如果我将 OR 替换为 AND,则查询会执行。

    public IEnumerable<Asset> GetAssets(AssetSearch search)
    {
        var list = new List<IMongoQuery>();

        if (!string.IsNullOrEmpty(search.Text))
        {
            list.Add(Query.Or(
                Query.Text(search.Text), 
                Query<Asset>.Matches(a => a.FileName, search.Text)
            ));
        }

        if (search.FolderId.HasValue)
            list.Add(Query<Asset>.EQ(a => a.FolderId, search.FolderId.Value));

        return AssetCollection.Find(Query.And(list));
    }

使用 (search.Text = "football") 执行时出现此错误

"QueryFailure flag was Unable to execute query: error processing query: ns=db.assets limit=0 skip=0 Tree: $and $or filename regex /football/ TEXT : query=football, language=, tag=NULL folderId == ObjectId('55d72ad19b958b1e7c0506ff') Sort: {} Proj: {} No query solutions (response was { "$err" : "Unable to execute query: error processing query: ns=db.assets limit=0 skip=0\nTree: $and\n $or\n filename regex /football/\n TEXT : query=football, language=, tag=NULL\n folderId == ObjectId('55d72ad19b958b1e7c0506ff')\nSort: {}\nProj: {}\n No query solutions", "code" : 17007 })."

【问题讨论】:

  • 毫无疑问,带有“AND”的 BSON 解释完全忽略了该条件,因为 MongoDB 查询中的所有查询参数无论如何都是隐含的“AND”条件。问题是 $or 从 BSON 文档的顶层抽象出来,而 $text 搜索操作只能在顶层使用。所以不在{ "$or"": [ { "$text": { "$search": "term" } }] } 的隐含结构内。这与索引选择有关,就像执行“文本搜索”的方式一样,将结果“混合”在按与外部条件的相关性排序的输出中是没有意义的
  • $text 搜索操作只能在顶层使用 -- 不知道。所以我想我需要编写 2 个单独的查询并组合结果?我真的很喜欢文本搜索的功能......但我还需要检索像 football.jpg 这样的结果,这似乎只能使用 $match 来实现。

标签: c# mongodb mongodb-query


【解决方案1】:

我尝试使用文本过滤器,但它对我不起作用。因此,任何人都想通过单个查询在多个列中进行搜索。你可以试试这个。

var filter = Builders<Book>.Filter.Or(
    Builders<Book>.Filter.Where(p=>p.Title.ToLower().Contains(query.ToLower())),
    Builders<Book>.Filter.Where(p => p.Publisher.ToLower().Contains(query.ToLower())),
    Builders<Book>.Filter.Where(p => p.Description.ToLower().Contains(query.ToLower()))
            );
List<Book> books = Collection.Find(filter).ToList();

【讨论】:

    猜你喜欢
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2021-10-30
    相关资源
    最近更新 更多