I'm learning elastic for a new project. I have a index with format:
{
"content_id": "bbbbbb",
"title": "content 2",
"data": [
{
"id": "xx",
"value": 3,
"tags": ["a","b","c"]
},
{
"id": "yy",
"value": 1,
"tags": ["e","d","c"]
}
]
}
How can i make a query to search contents that have at least one element in data that include tags "a" and "b" ?
thanks so much !!
How can i make query or re design my format data to easy make new query ?
CodePudding user response:
Working with lists and nested documents in Elasticsearch is a bit tricky.
When creating the index, you need to specify the mapping for the nested documents. You can do this by adding a mapping for the data field.
PUT /my_index
{
"mappings": {
"doc": {
"properties": {
"data": {
"type": "nested"
}
}
}
}
}
If you have already created the index, you should delete it first, then create it again with the mapping.
Before deleting the index, you can reindex (copy) the data to a new index.
Now you can query the data field using the nested query:
GET /my_index/_search
{
"query": {
"nested": {
"path": "data",
"query": {
"terms": {
"data.tags": [
"j",
"b",
"c"
]
}
}
}
}
}
CodePudding user response:
If the requirement is to get the document if at least one object in data
contains a
and b
both, then you need to specify the nested
mapping as suggested by @ChamRun.
But for getting the results having a
and b
both, you need to use the below query :
{
"query": {
"nested": {
"path": "data",
"query": {
"bool": {
"must": [
{
"term": {
"data.tags": "a"
}
},
{
"term": {
"data.tags": "b"
}
}
]
}
}
}
}
}