MongoDB 全文和部分文本搜索

100

环境:

  • MongoDB(3.2.0)与Mongoose

集合:

  • 用户

文本索引创建:

  BasicDBObject keys = new BasicDBObject();
  keys.put("name","text");

  BasicDBObject options = new BasicDBObject();
  options.put("name", "userTextSearch");
  options.put("unique", Boolean.FALSE);
  options.put("background", Boolean.TRUE);
  
  userCollection.createIndex(keys, options); // using MongoTemplate

文档:

  • {"name":"LEONEL"}

查询:

  • db.users.find( { "$text" : { "$search" : "LEONEL" } } ) => 找到
  • db.users.find( { "$text" : { "$search" : "leonel" } } ) => 找到(搜索区分大小写为false)
  • db.users.find( { "$text" : { "$search" : "LEONÉL" } } ) => 找到(搜索区分变音符号为false)
  • db.users.find( { "$text" : { "$search" : "LEONE" } } ) => 找到(部分匹配搜索)
  • db.users.find( { "$text" : { "$search" : "LEO" } } ) => 没有找到(部分匹配搜索)
  • db.users.find( { "$text" : { "$search" : "L" } } ) => 没有找到(部分匹配搜索)

为什么使用"LEO"或"L"作为查询条件会得到0个结果呢?

不允许在文本索引搜索中使用正则表达式。

db.getCollection('users')
     .find( { "$text" : { "$search" : "/LEO/i", 
                          "$caseSensitive": false, 
                          "$diacriticSensitive": false }} )
     .count() // 0 results

db.getCollection('users')
     .find( { "$text" : { "$search" : "LEO", 
                          "$caseSensitive": false, 
                          "$diacriticSensitive": false }} )
.count() // 0 results

MongoDB文档:


12
此问题涉及使用文本索引进行部分搜索和大小写不敏感搜索。请不要标记此问题为重复的,@LucasCosta。 - Leonel
你尝试过使用/LEO/i吗?你可以在MongoDB中使用正则表达式来搜索值。 - BrTkCa
@LucasCosta 的文本索引搜索不允许使用正则表达式。 - Leonel
无索引搜索: https://dev59.com/gVsW5IYBdhLWcg3wSVqM#48250561 - TomoMiha
11个回答

-5
import re

db.collection.find({"$or": [{"your field name": re.compile(text, re.IGNORECASE)},{"your field name": re.compile(text, re.IGNORECASE)}]})

8
仅提供代码的答案并不受鼓励,因为它们对于未来的读者提供的信息不够充分,请在你编写的代码上提供一些解释说明。 - WhatsThePoint
谢谢,使用像你展示的正则表达式对于 pymongo 是有效的。 - nmz787

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接