Filter documents based on different values in same field in different documents

Hi,

I have a question regarding the requirement in elastic-search. I have following documents in my index.

{
"name":"a1",
"userId": 1,
"tag":"tag1"
},

{
"name":"abc",
"userId":1,
"tag":"tag2"
},

{
"name":"a2",
"userId":2,
"tag":"tag1"
},

{
"name":"abc2",
"userId":2,
"tag":"tag2"
},

{
"name":"abc3",
"userId":2,
"tag":"tag3"
}
Now if my query is to fetch me all the documents for the userID who has tag values as "tag1" AND "tag3" i.e. in this case documents returned are

{
"name":"a2",
"userId":2,
"tag":"tag1"
}
{
"name":"abc3",
"userId":2,
"tag":"tag3"
}
so in this case document containing tag values as "tag1" but for userId 1 will not be returned as for that userID we do not have document for "tag3".

I was checking whether aggregation pipeline or groovy script would work however I am stuck. So can you please suggest what elastic query would be required for this.

In Future there might be requirement similar to AND I might have to work on NOT i.e. " tag2 NOT tag3 " then I have to show only
{
"name":"abc",
"userId":1,
"tag":"tag2"
}

What sort of query do you want to use?

Because AND means both tags must exist in the results. See https://www.elastic.co/guide/en/elasticsearch/reference/5.0/query-dsl-query-string-query.html#query-string-syntax

Hi,

Please correct me if I am wrong - 'AND' will check if both the keywords are present in the field of the same document.

However the requirement here is - to show the documents of the user for which tag field contains values "tag1" as well as "tag3". In one document there would be only one value of the tag. i.e. in the single document either tag1 will be present or tag3 and not both values. So in my case (mentioned in the first post) I want to fetch documents pertaining to user with userid2 as for this user the tag field has values as 'tag1' as well as 'tag3', which are present in different documents.

Please let me know if I have been able to explain the problem.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.