首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >文本搜索- mongodb

文本搜索- mongodb
EN

Stack Overflow用户
提问于 2016-02-17 08:08:48
回答 1查看 360关注 0票数 1

我在应用程序中使用mongo文本搜索。

索引:

代码语言:javascript
复制
db.test.createIndex(
    {
        title: 'text',
        description: 'text'
    },
    {
        name: "TextIndex",
        weights: {
           title: 10,
           description: 1
        }
    }
)

得分:

代码语言:javascript
复制
title : 10
description : 1

文件:

代码语言:javascript
复制
db.test.insert(
  [
    { _id: 1, title: "agent de production", description: "production or agent"},
    { _id: 2, title: "agent test production", description: "agent" },
    { _id: 3, title: "production agent", "description" : "production"},
    { _id: 4, title: "agent", "description" : "production"},
    { _id: 5, title: "test", "description" : "production example agent"},
  ]
)

问题

所以如果我搜索“代理生产”

结果应该是

代码语言:javascript
复制
[
  { _id: 1, title: "agent de production", description: "production or agent"},
  { _id: 2, title: "agent test production", description: "agent" },
  { _id: 3, title: "production agent", "description" : "production"},
  { _id: 5, title: "test", "description" : "production example agent"},
]

我试过的是:

代码语言:javascript
复制
db.test.find({"$text" : {"$search" : "\"agent production\""}}); Query result does not match with the expected result.

结果:0

查询短语:db.test.find({"$text“:{"$search”:“\”代理\“生产\”})

结果

代码语言:javascript
复制
{ "_id" : 5, "title" : "test", "description" : "production example agent" }
{ "_id" : 1, "title" : "agent de production", "description" : "production or agent" }
{ "_id" : 3, "title" : "production agent", "description" : "production" }
{ "_id" : 2, "title" : "agent test production", "description" : "agent" }
{ "_id" : 4, "title" : "agent", "description" : "production" }

任何建议都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-18 06:08:30

让我们回顾一下$search查询中的$text字符串是如何工作的。如果给出一个短语,就像在"$search": "\"agent production\""中一样,只有与短语匹配的索引字段的文档才能获得非零分数。这就解释了为什么在这种情况下没有发现结果。但是,指定"$search": "\"production agent\""将使文档与_id: 3匹配。如果给出了单独的单词/术语,如在"$search": "\"agent\" \"production\""中,任何带有索引字段的文档都会得到分数。这解释了为什么返回带有_id: 4的文档,因为它在单个字段中不一定同时包含两个术语,正如您在期望的结果中所显示的那样。

要强制两个搜索项都包含在单个字段中,您需要向查询中添加其他子句。您可以执行文本搜索以对文档进行评分,并使用regex进一步过滤文档,如下所示:

代码语言:javascript
复制
db.test.find( { $and: [ { "$text": { "$search": "\"agent\" \"production\"" } },
    { $or: [
        { $and: [ { title: /agent/i }, { title: /production/i } ] }, 
        { $and: [ { description: /agent/i }, { description: /production/i } ] }
    ] }
 ] }, { score: { $meta: "textScore" } } ).sort( { score: { $meta: "textScore" } } )

请注意,添加textScore是因为默认情况下文档没有根据分数进行排序。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35451058

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档