Mongodb文本搜索多个字段

编程入门 行业动态 更新时间:2024-10-24 08:29:38
本文介绍了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文本搜索多个字段

本文发布于:2023-11-22 13:56:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617708.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   字段   文本   Mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!