gpt4 book ai didi

MongoDB 对结构未知的子文档进行文本搜索

转载 作者:可可西里 更新时间:2023-11-01 09:44:13 26 4
gpt4 key购买 nike

我有一组文档,每个文档都有一个嵌套文档,在这个例子中名为“属性”的文档:

document1: {
description: 'text text etc',
attributes: {
Name: 'Alice',
Height: '170',
FavouriteColour: 'Blue'
}
}

document2: {
description: 'more text etc',
attributes: {
Name: 'Bob',
State: 'NY'
}
}

我不知道键的名称是什么,因为它们是用户定义的。

我想对该文档中所有属性的值执行文本搜索,而不必指定键,但为了执行文本搜索,我只需要一个文本索引来表示 $text。查询,所以这是不可能的:

db.collection.aggregate([
{$match: {$text: {$search: 'NY'}}},
{$group: {_id: {$meta: "textScore"}, count: {$sum: 1}}}
])

由于我不知道我可能拥有哪些属性,是否有办法解决这个问题并对属性值执行文本搜索并返回与输入匹配的文档?

最佳答案

是的,但是。

是的:您可以像这样用字符串内容索引所有字段:

> db.collection.ensureIndex({ "$**": "text" }, { name: "TextIndex" })

参见 Create a Text Index .

但是:如果你能避免的话,不要让你的数据有未知的结构,尤其是当你让键和值由用户定义时。你能做类似的事情吗

{
"description" : "text text etc",
"attributes" : [
{ "key" : "Name", "value" : "Alice" },
{ "key" : "Height", "value" : "170" },
{ "key" : "FavouriteColour", "value" : "Blue" }
]
}

相反?参见 How to Model Dynamic Attributes .

关于MongoDB 对结构未知的子文档进行文本搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26022320/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com