5

I am a beginner in elasticsearch and I want to add an index for the field inside a jsonb field I am having. This is not a nested relationship.

I am having table payload with fields id (integer),user_id(integer),data(jsonb).

Sample jsonb value is like:

{"name" => "Test User", "values" => {"age" => 24, "gender" => "male"}, "married": false}

I want to add index for the "gender" field inside "values" section of "data"(jsonb column).

Database is postgres.

I have added the index configuration as follows:

  mappings do
    indexes :id,      type: 'integer'
    indexes :user_id, type: 'integer'

    indexes :data do
      indexes :gender
    end
  end

Is this right?

I am getting exact results for the query,

{"query": {
    "term": {
        "user_id": 1
    }
}}

but not for this query

{"query": {
    "term": {
        "gender": "male"
    }
}}

Thanks in advance !!!

Mohammad
  • 21,175
  • 15
  • 55
  • 84

1 Answers1

3

I use nested type to define the jsonb object:

  settings index: { number_of_shards: 1 } do
    mappings dynamic: 'false' do
      indexes :id, type: 'integer'
      indexes :user_id, type: 'integer'
      indexes :name, type: 'text'
      indexes :data, type: 'nested' do
        indexes :gender, type: 'text'
        indexes :age, type: 'integer'
      end
    end
  end

Read here https://www.elastic.co/guide/en/elasticsearch/reference/current/object.html for more information about JSON documents.

If you have dynamic fields in the JSONB objects then you can define the index like this:

  settings index: { number_of_shards: 1 } do
    mappings dynamic: 'false' do
      indexes :id, type: 'integer'
      indexes :user_id, type: 'integer'
      indexes :name, type: 'text'
      indexes :data, dynamic: 'true' do
      end
    end
  end
phlegx
  • 2,618
  • 3
  • 35
  • 39