2017-02-20 40 views
0

我需要使用pymongo MongoDB进行字符串搜索,它检查字符串中的子字符串匹配,而与字顺序和大小无关。PyMongo:子字符串匹配独立于字顺序

我们来看一个例子。

在我的收藏品也有类似如下的文件:

{'_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)中执行这种文本搜索是否有效?

回答

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

+0

如果我没有错,'$ text'索引不支持子字符串的部分匹配... – floatingpurr