Mongodb - 如何为 JSON 字段创建全文索引?

Rip*_*ley 3 indexing mongodb

这个问题是关于为 mongo db 集合创建全文索引。

该集合包含以下文档:

{
    "_id" : ObjectId("5b44cd9dec97d60001efb75d"),
    "action_id" : NumberLong(0),
    "transaction_id" : "ad77575a8b4f52e477682e712b1cbd884299468db6a94d909f90c6961cea9b02",
    "authorization" : [
            {
                    "permission" : "active",
                    "actor" : "eosio"
            }
    ],
    "handler_account_name" : "eosio.token",
    "name" : "transfer",
    "data" : {
            "from" : "eosio",
            "to" : "b1",
            "quantity" : "10.0000 EOS",
            "memo" : "Never doubt that a small group of thoughtful, committed citizens can change the world; indeed, it's the only thing that ever has - eosacknowledgments.io"
    },
    "createdAt" : ISODate("2018-07-10T15:15:41.750Z")}
Run Code Online (Sandbox Code Playgroud)

我正在尝试为“数据”字段中的字符串字段创建文本索引。它可以用

db.Actions.ensureIndex({"$**":"text"})
Run Code Online (Sandbox Code Playgroud)

但是根据这里的 mongo 文档https://docs.mongodb.com/manual/core/index-text/这将在整个文档的所有文本字段上创建索引,这是一种浪费。

我可以实现相同的索引行为,但仅适用于“数据”下的文本字段吗?

mat*_*Pen 6

正如官方文档所说,

MongoDB provides text indexes to support text search queries on string content.
Text indexes can include any field whose value is a string or an array of string elements.
Run Code Online (Sandbox Code Playgroud)

但是您没有字符串或字符串数​​组,而是 json 对象。实现您想要的方法是使用数据子文档的每个字段手动创建文本索引:

db.Actions.createIndex(
  { 
  "data.from" : "text", 
  "data.memo" : "text", 
  "data.quantity" : "text", 
  "data.to" : "text"
  }
)
Run Code Online (Sandbox Code Playgroud)