I need to use elastic search in nestjs to query to retrieve some result from index.
Requirements: I need all results including access_level: "Restricted" and access_level: "Unrestricted" result, but the data with access_level: "Restricted" will excludes: ['image_path'] field in the search result.
However the "Unrestricted" result will remain the same in the result list including 'image_path' field how to do elastic search to do it nestjs do with 1 query
body = {
from: 0,
size: 0,
_source: {
excludes: ["image_path"] // when access_level: Restricted
},
query: {
bool: {
must:[
{
match: {
access_level: "Restricted"
},
match: {
access_level: "Unrestricted"
}
}
],
should: []
},
},
};
On the elasticsearch side this is handled by the feature called field level security. It's premium feature. If you want to roll out your own security solution, which is quite difficult here, you will have to implement it outside of elasticsearch. One possible solution is to store restricted images in another field. This way you can just remove this field from the source regardless of the state of the record. If the
access_levelfield indexed as keyword, you could also check it in a script and returnimage_pathfrom the script only if access_level is unrestricted. Please note that unlike the built-in field level security solution that will only remove the field from the source on the output. All other operations including aggregations, etc will still have access to this field.