I have POSTS that can have many TAGS. I only want my query to return POSTS with a unique tag and no others. For example.
posts: [
{ id: 1
tags: [hello, world]
...
}
{ id: 2
tags: [hello]
}
]
The following:
search?q=tag:hello
Should only return:
posts: [
{ id: 2
tags: [hello]
}
]
How would I accomplish this using elastic search?
Elasticsearch uses lucene underneath, which is an inverted index. Roughly, it indexes terms and allows you to query for documents based on terms. If you search for a term, of course it will return the documents that contain that term. Tags are terms too, so the logic is the same. I don’t know how you could tell lucene to return the documents which contain only that term, or the other way around, to exclude all the documents which contain any other term.
You can achieve what you want sending the tags altogether in a single value, and setting your mapping for that field to
"index" : "not_analyzed". This way you would be indexing a single tag term per document, containing all the tags related to it. If you search for a specific tag the documents which contain only that specific tag would be returned. On the other hand if a document has multiple tags you need to search for all of them together in order to get back that document. Your requirement looks quite strange to me, but if that’s what you want this way you should be able to do it.