Field and document level security helps control who can see specific parts of your data. It keeps sensitive information safe by limiting access.
0
0
Field and document level security in Elasticsearch
Introduction
You want to hide salary details from most employees but show them to HR.
You need to show only customer names but not their contact info to support staff.
You want to restrict access to certain documents based on user roles.
You want to protect confidential fields like social security numbers from being visible.
You want to allow users to search only within documents they own.
Syntax
Elasticsearch
PUT /_security/role/role_name
{
"indices": [
{
"names": ["index_name"],
"privileges": ["read"],
"field_security": {
"grant": ["field1", "field2"]
},
"query": {
"term": {
"user_id": "{{_user.username}}"
}
}
}
]
}field_security.grant lists fields the user can see.
query filters documents the user can access.
Examples
This role lets HR read only name, salary, and department fields from the employees index.
Elasticsearch
PUT /_security/role/hr_role
{
"indices": [
{
"names": ["employees"],
"privileges": ["read"],
"field_security": {
"grant": ["name", "salary", "department"]
}
}
]
}This role lets support staff read only name and email fields from customers in the 'us-east' region.
Elasticsearch
PUT /_security/role/support_role
{
"indices": [
{
"names": ["customers"],
"privileges": ["read"],
"field_security": {
"grant": ["name", "email"]
},
"query": {
"term": {
"region": "us-east"
}
}
}
]
}This role allows users to read only documents they own, no field restrictions.
Elasticsearch
PUT /_security/role/owner_role
{
"indices": [
{
"names": ["documents"],
"privileges": ["read"],
"query": {
"term": {
"owner": "{{_user.username}}"
}
}
}
]
}Sample Program
This example creates a role that lets users read only the report_name and total_revenue fields from financial_reports index, but only for documents where department is 'finance'.
When a user with this role searches, they see only allowed fields and documents.
Elasticsearch
PUT /_security/role/finance_role
{
"indices": [
{
"names": ["financial_reports"],
"privileges": ["read"],
"field_security": {
"grant": ["report_name", "total_revenue"]
},
"query": {
"term": {
"department": "finance"
}
}
}
]
}
# After creating this role, assign it to a user to restrict their access.
GET /financial_reports/_search
{
"query": {
"match_all": {}
}
}OutputSuccess
Important Notes
Field and document level security works together to limit data exposure.
Use {{_user.username}} to personalize document access based on the logged-in user.
Remember to assign roles to users after creating them.
Summary
Field level security controls which fields a user can see.
Document level security controls which documents a user can access.
Together, they protect sensitive data in Elasticsearch.