madan ram
madan ram

Reputation: 1270

searching for subdocument in elastic search

I have a document of form

'search':
[
    {
        id:'1',
        "content": [
            {
                "text": "random text .....",
                "time": 150.023
            },
            {
                "text": "random text .....",
                "time": 160.023
            }
          ]
    },

    {
        id:'2',
        "content": [
            {
                "text": "random text .....",
                "time": 150.023
            },
            {
                "text": "random text .....",
                "time": 160.023
            }
          ]
    }
    .
    .
    .
]

I want to search on text field and get its id, text and time eg

my sample document and index search looks like below

'search':
[
    {
        id:'1',
        "content": [
            {
                "text": "Algorithm and Data structure",
                "time": 150.023
            },
            {
                "text": "Selection Sort",
                "time": 160.023
            }
          ]
    },

    {
        id:'2',
        "content": [
            {
                "text": "Database and schema",
                "time": 1530.023
            }
          ]
    }
    .
    .
    .
]

now when I search for "text:Algorithm" then I need id:'1', "text": "Algorithm and Data structure" and "time": 150.023.

How can I use elasticsearch get above result. please provide some solution. Thank you in advance.

Upvotes: 0

Views: 122

Answers (1)

Vineeth Mohan
Vineeth Mohan

Reputation: 19253

In elasticsearch , search is per document. You can get certain fields alone in search but not the way you are looking for in an array. The best solution here would be to declare search field as nested so that you can do element specific search and then get the whole document and then retrieve the element you are looking for on the client side.

OR , you can change your data modelling and model a document around an element of search.

This means that instead of maintaining a single document as -

'search':
[
    {
        id:'1',
        "content": [
            {
                "text": "random text .....",
                "time": 150.023
            },
            {
                "text": "random text .....",
                "time": 160.023
            }
          ]
    },

    {
        id:'2',
        "content": [
            {
                "text": "random text .....",
                "time": 150.023
            },
            {
                "text": "random text .....",
                "time": 160.023
            }
          ]
    }
    .
    .
    .
]

You can maintain model multiple documents per above document where a single document looks like -

{
  "id": "1",
  "content": {
    "text": "random text .....",
    "time": 150.023
  }
}

Upvotes: 1

Related Questions