首页 > 代码库 > Mongodb全文检索

Mongodb全文检索

  1. //插入测试数据 有列name和description
  2. > db.stores.insert(
  3. ... [
  4. ... { _id: 1, name: "Java Hut", description: "Coffee and cakes" },
  5. ... { _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },
  6. ... { _id: 3, name: "Coffee Shop", description: "Just coffee" },
  7. ... { _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing" },
  8. ... { _id: 5, name: "Java Shopping", description: "Indonesian goods" }
  9. ... ]
  10. ... )
  11. BulkWriteResult({
  12.    "writeErrors" : [ ],
  13.    "writeConcernErrors" : [ ],
  14.    "nInserted" : 5,
  15.    "nUpserted" : 0,
  16.    "nMatched" : 0,
  17.    "nModified" : 0,
  18.    "nRemoved" : 0,
  19.    "upserted" : [ ]
  20. })
  21. //在stores上建立所以 包含name列和description都是文本
  22. > db.stores.createIndex( { name: "text", description: "text" } )
  23. {
  24.    "createdCollectionAutomatically" : false,
  25.    "numIndexesBefore" : 1,
  26.    "numIndexesAfter" : 2,
  27.    "ok" : 1
  28. }
  29. //执行全文检索 会将关键字分词 然后匹配结果还可以 由于数据量小 速度就测不出来了
  30. > db.stores.find( { $text: { $search: "java coffee shop" } } )
  31. { "_id" : 3, "name" : "Coffee Shop", "description" : "Just coffee" }
  32. { "_id" : 1, "name" : "Java Hut", "description" : "Coffee and cakes" }
  33. { "_id" : 5, "name" : "Java Shopping", "description" : "Indonesian goods" }

优势:实时的全文检索。

不知道性能如何,不支持高亮这种展示,只有在3.2+的版本才支持中文分词。

大致了解下,暂时不会用到,以后用到可以详细看手册:

https://docs.mongodb.com/manual/text-search/

Mongodb全文检索