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 !!!

2
  • Looks like this one might help you here: michael.otacoo.com/postgresql-2/… Commented Jul 6, 2016 at 7:47
  • @TarynEast.. Thanks..I have edited the question. I am looking for adding index in elasticsearch. Commented Jul 6, 2016 at 7:57

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.