Mongodb文本搜索多个字段 [英] Mongodb text search multiple fields

查看:268
本文介绍了Mongodb文本搜索多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个mongodb文档,看起来像这样:

I have a mongodb document which looks like this:

document
  title
  suburb
  id
  date

我想添加一个搜索功能,使人们可以通过郊区和标题搜索文档.我正在使用文本搜索功能,我想要这样的东西:

And I want to add a search feature where people can search for documents via suburb and title. I am using the text search feature and I want something like this:

var search = {
  $and : [
    { $search:'melbourne' },   // Search in suburb
    { $search:'hello world' }  // As well as in title 
  ]
};
db.ad.find(search).sort([['date', -1]]).limit(10).skip(0, callback);

但是上面的代码不起作用.我已经索引了郊区和标题字段并启用了文本搜索.

But the above code is not working. I have indexed both suburb and title fields and enabled text search.

有人知道如何制作一个支持两个不同字段的文本搜索的mongodb子句吗?

Does anyone know how to make a mongodb clause supporting text search for two different fields?

我在mongodb v 2.6中使用mongojs

I am using mongojs with mongodb v 2.6

推荐答案

mongodb中的文本搜索"概念不能那样工作.取而代之的是,这里的概念是您在文本索引" 并仅搜索条款.

The "text search" concept in mongodb does not work like that. Instead the concept here is that you define "mutiple fields" in your "text index" and just search for the terms.

假设您有这样的东西":

Let's say you have "stuff" like this:

{ "_id" : ObjectId("55ba22294bde97b581332979"), "title" : "Hello there" },
{ "_id" : ObjectId("55ba22414bde97b58133297a"), "title" : "Hello world" },
{
    "_id" : ObjectId("55ba22594bde97b58133297b"),
    "title" : "Hello world",
    "suburb" : "melbourne"
}

然后,我决定创建一个像这样的文本索引:

Then I decide to create a text index like this:

db.junk.createIndex(
   { "title": "text", "suburb": "text" },
   { "weights": {  "title": 10 } }
)

然后,我使用 $text 进行搜索> :

db.junk.find(
   { "$text": { "$search": "Hello World Melbourne" } },
   { "score": { "$meta": "textScore" } }
).sort({ "score": { "$meta": "textScore" } })

哪个给出结果:

{
    "_id" : ObjectId("55ba22594bde97b58133297b"),
    "title" : "Hello world",
    "suburb" : "melbourne",
    "score" : 11.5
},
{
    "_id" : ObjectId("55ba22414bde97b58133297a"),
    "title" : "Hello world",
    "score" : 1.5
},
{
    "_id" : ObjectId("55ba22294bde97b581332979"),
    "title" : "Hello there",
    "score" : 1
}

两个"都在索引中指定的所有字段中进行搜索,并且在这种情况下还考虑了赋予郊区"字段的额外权重",以使其成为更受欢迎的排名.

Which "both" searches over all the fields specified in the index and also considers the additional "weight" as given to the "suburb" field in this case to make it an even more popular ranking.

因此,您无需在术语中使用其他条件,只需将所有"这些术语放在一个"文本查询字符串中,即可在多个字段中进行搜索.

So you don't use additional conditons in terms, you put "all" of the terms in the "one" text query string to search on multiple fields.

这篇关于Mongodb文本搜索多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆