【问题标题】:PyMongo: substrings match independent of words orderPyMongo:子字符串匹配独立于单词顺序
【发布时间】:2017-02-20 21:36:23
【问题描述】:

我需要使用 pymongo MongoDB 进行字符串搜索,它检查键中的子字符串匹配,与单词顺序和大小写无关。

让我们看一个例子。

在我的收藏中有如下文件:

{'_id':..., 'key': 'the foo'}
{'_id':..., 'key': 'the bar'}
{'_id':..., 'key': 'the baz'}

如果我在key 中搜索'key''Fo tHe''foo t''foo the',我想得到{'_id':..., 'key': 'the foo'}

我发现的最佳解决方案是通过 pymongo 以这种方式使用正则表达式:

query = {'key': {'$regex' : my_string, '$options':'i'}}
mycollection.find(query)

但是这个解决方案并不能完全满足我的要求。例如,如果my_string = 'foo the'(倒序),它不会返回文档。

有没有一种有效的方法可以在 pymongo (MongoDB) 中执行这种文本搜索?

【问题讨论】:

    标签: mongodb pymongo


    【解决方案1】:

    尝试全文索引:

    mycollection.create_index([("foo", "text")])
    

    执行一次,然后:

    for doc in mycollection.find(
        {"$text": {"$search": "foo the"}}
    ).sort({"score": {"$meta": "textScore"}}):
        print(doc)
    

    参见MongoDB Text Indexessort by meta

    【讨论】:

    • 如果我没记错的话,$text 索引不支持子字符串的部分匹配...
    猜你喜欢
    • 1970-01-01
    • 2015-06-06
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    相关资源
    最近更新 更多