2017-02-20 65 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