Reputation: 39
I am having nested array fields, I need to query and filter the records for that. Sample
"test":{
"name":[
{
"name": "vanaraj",
"Age" : 26
},
{
"name": "vanaraj",
"Age" : 10
},
{
"name": "ranjit",
"Age" : 26
},
]
}
Here how I need the query for below conditions, 1. Where Name is equal to both ["vanaraj","ranjit"] to fetch 2. Add condition where Age > 25 for only "vanaraj"
I need a query like below, but it is not working.
{
"query": {
"bool": {
"filter": [
{
"nested": {
"path": "data.test.name",
"query": {
"bool": {
"filter": [
{
"terms": {
"data.test.name.name": ["vanaraj","ranjit"]
}
}
]
}
}
}
},
{
"nested": {
"path": "data.test.name",
"query": {
"bool": {
"filter": [
{
"term": {
"data.test.name.name": "vanaraj"
}
},
{
"range": {
"data.test.name.Age": {
"gt": 25
}
}
}
]
}
}
}
}
]
}
}
}
Mapping :
{
"mappings":{
"properties":{
"test":{
"properties":{
"name":{
"type":"nested",
"properties":{
"Age":{
"type":"long"
},
"name":{
"type":"text",
"fields":{
"keyword":{
"type":"keyword",
"ignore_above":256
}
}
}
}
}
}
}
}
}
}
Upvotes: 1
Views: 76
Reputation: 8840
Based on your further clarification, the below code should help you:
POST <your_index_name>/_search
{
"query": {
"bool": {
"should": [
{
"nested": {
"path": "test.name",
"query": {
"bool": {
"must": [
{
"match": {
"test.name.name": "vanaraj"
}
},
{
"range": {
"test.name.Age": {
"gte": 26
}
}
}
]
}
}
}
},
{
"nested": {
"path": "test.name",
"query": {
"bool": {
"must": [
{
"match": {
"test.name.name": "ranjith"
}
}
]
}
}
}
}
]
}
}
}
The above solution would return you all the documents having name
as ranjith
OR if name
is vanaraj
and age > 25
Summary of query:
Bool
- Should
- Must clause for name=vanaraj and age >= 26
- Must clause for name=ranjith
POST <your_index_name>/_search
{
"query": {
"bool": {
"should": [
{
"nested": {
"path": "test.name",
"query": {
"bool": {
"must": [
{
"match": {
"test.name.name": "vanaraj"
}
},
{
"range": {
"test.name.Age": {
"gte": 26
}
}
}
]
}
}
}
},
{
"nested": {
"path": "test.name",
"query": {
"bool": {
"must": [
{
"terms": {
"test.name.name": [
"abc",
"ranjit"
]
}
}
]
}
}
}
}
],
"must_not": [
{
"nested": {
"path": "test.name",
"query": {
"bool": {
"must": [
{
"terms": {
"test.name.name": [
"vanaraj"
]
}
},{
"range": {
"test.name.Age": {
"lte": 25
}
}
}
]
}
}
}
}
]
}
}
}
Please run the above and let me know if this helps!
Upvotes: 1