Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb - How to create full text index for a JSON field?

This question is about creating full text index for a mongo db collection.

The collection contains documents like:

{
    "_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")}

I'm trying to create text index for string fields in "data" field. It can be done with

db.Actions.ensureIndex({"$**":"text"})

But according to mongo document here https://docs.mongodb.com/manual/core/index-text/ this will create index on all text fields of the whole document, which is a waste.

Can I achieve the same index behavior, but only for text fields under "data"?

like image 653
Ripley Avatar asked Oct 19 '25 10:10

Ripley


1 Answers

As the official doc says,

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.

But you don't have string or array of strings, but a json object. The way to achieve what you want is to manually create your text index with every field of your data subdocument :

db.Actions.createIndex(
  { 
  "data.from" : "text", 
  "data.memo" : "text", 
  "data.quantity" : "text", 
  "data.to" : "text"
  }
)
like image 144
matthPen Avatar answered Oct 21 '25 02:10

matthPen