Advanced search development guidelines

This page includes information about developing and working with Elasticsearch.

Information on how to enable Elasticsearch and perform the initial indexing is in the Elasticsearch integration documentation.

Deep Dive

In June 2019, Mario de la Ossa hosted a Deep Dive (GitLab team members only: on the GitLab Elasticsearch integration to share his domain specific knowledge with anyone who may work in this part of the codebase in the future. You can find the recording on YouTube, and the slides on Google Slides and in PDF. Everything covered in this deep dive was accurate as of GitLab 12.0, and while specific details might have changed, it should still serve as a good introduction.

In August 2020, a second Deep Dive was hosted, focusing on GitLab-specific architecture for multi-indices support. The recording on YouTube and the slides are available. Everything covered in this deep dive was accurate as of GitLab 13.3.

Supported Versions

See Version Requirements.

Developers making significant changes to Elasticsearch queries should test their features against all our supported versions.

Setting up development environment

See the Elasticsearch GDK setup instructions

Helpful Rake tasks

  • gitlab:elastic:test:index_size: Tells you how much space the current index is using, as well as how many documents are in the index.
  • gitlab:elastic:test:index_size_change: Outputs index size, reindexes, and outputs index size again. Useful when testing improvements to indexing size.

Additionally, if you need large repositories or multiple forks for testing, consider following these instructions

How does it work?

The Elasticsearch integration depends on an external indexer. We ship an indexer written in Go. The user must trigger the initial indexing via a Rake task but, after this is done, GitLab itself will trigger reindexing when required via after_ callbacks on create, update, and destroy that are inherited from /ee/app/models/concerns/elastic/application_versioned_search.rb.

After initial indexing is complete, create, update, and delete operations for all models except projects (see #207494) are tracked in a Redis ZSET. A regular sidekiq-cron ElasticIndexBulkCronWorker processes this queue, updating many Elasticsearch documents at a time with the Bulk Request API.

Search queries are generated by the concerns found in ee/app/models/concerns/elastic. These concerns are also in charge of access control, and have been a historic source of security bugs so pay close attention to them!

Custom routing

Custom routing is used in Elasticsearch for document types that are associated with a project. The routing format is project_<project_id>. Routing is set during indexing and searching operations. Some of the benefits and tradeoffs to using custom routing are:

  • Project scoped searches are much faster.
  • Routing is not used if too many shards would be hit for global and group scoped searches.
  • Shard size imbalance might occur.

Existing analyzers and tokenizers

The following analyzers and tokenizers are defined in ee/lib/elastic/latest/config.rb.



Used when indexing blobs’ paths. Uses the path_tokenizer and the lowercase and asciifolding filters.

See the path_tokenizer explanation below for an example.


Used in blobs and commits. Uses the sha_tokenizer and the lowercase and asciifolding filters.

See the sha_tokenizer explanation later below for an example.


Used when indexing a blob’s filename and content. Uses the whitespace tokenizer and the word_delimiter_graph, lowercase, and asciifolding filters.

The whitespace tokenizer was selected to have more control over how tokens are split. For example the string Foo::bar(4) needs to generate tokens like Foo and bar(4) to be properly searched.

See the code filter for an explanation on how tokens are split.



This is a custom tokenizer that uses the edgeNGram tokenizer to allow SHAs to be searchable by any sub-set of it (minimum of 5 chars).


240c29dc7e becomes:

  • 240c2
  • 240c29
  • 240c29d
  • 240c29dc
  • 240c29dc7
  • 240c29dc7e


This is a custom tokenizer that uses the path_hierarchy tokenizer with reverse: true to allow searches to find paths no matter how much or how little of the path is given as input.


'/some/path/application.js' becomes:

  • '/some/path/application.js'
  • 'some/path/application.js'
  • 'path/application.js'
  • 'application.js'


  • Searches can have their own analyzers. Remember to check when editing analyzers.
  • Character filters (as opposed to token filters) always replace the original character. These filters can hinder exact searches.

Add a new document type to Elasticsearch

If data cannot be added to one of the existing indices in Elasticsearch, follow these instructions to set up a new index and populate it.


  • Ensure Elasticsearch is running:

    curl "http://localhost:9200"
  • Run Kibana to interact with your local Elasticsearch cluster. Alternatively, you can use Cerebro or a similar tool.
  • To tail the logs for Elasticsearch, run this command:

    tail -f log/elasticsearch.log`

See Recommended process for adding a new document type for how to structure the rollout.

Create the index

  1. Create a Search::Elastic::Types:: class in ee/lib/search/elastic/types/.
  2. Define the following class methods:
    • index_name: in the format gitlab-<env>-<type> (for example, gitlab-production-work_items).
    • mappings: a hash containing the index schema such as fields, data types, and analyzers.
    • settings: a hash containing the index settings such as replicas and tokenizers. The default is good enough for most cases.
  3. Add a new advanced search migration to create the index by executing scripts/elastic-migration and following the instructions. The migration name must be in the format Create<Name>Index.
  4. Use the Elastic::MigrationCreateIndex helper and the 'migration creates a new index' shared example for the specification file created.
  5. Add the target class to Gitlab::Elastic::Helper::ES_SEPARATE_CLASSES.
  6. To test the index creation, run in a console and check that the index has been created with the correct mappings and settings:

    curl "http://localhost:9200/gitlab-development-<type>/_mappings" | jq .`
    curl "http://localhost:9200/gitlab-development-<type>/_settings" | jq .`

Create a new Elastic Reference

Create a Search::Elastic::References:: class in ee/lib/search/elastic/references/.

The reference is used to perform bulk operations in Elasticsearch. The file must inherit from Search::Elastic::Reference and define the following methods:

include Search::Elastic::Concerns::DatabaseReference # if there is a corresponding database record for every document

override :serialize
def self.serialize(record)
   # a string representation of the reference

override :instantiate
def self.instantiate(string)
   # deserialize the string and call initialize

override :preload_indexing_data
def self.preload_indexing_data(refs)
   # remove this method if `Search::Elastic::Concerns::DatabaseReference` is included
   # otherwise return refs

def initialize
   # initialize with instance variables

override :identifier
def identifier
   # a way to identify the reference

override :routing
def routing
   # Optional: an identifier to route the document in Elasticsearch

override :operation
def operation
   # one of `:index`, `:upsert` or `:delete`

override :serialize
def serialize
   # a string representation of the reference

override :as_indexed_json
def as_indexed_json
   # a hash containing the document represenation for this reference

override :index_name
def index_name
   # index name

def model_klass
   # set to the model class if `Search::Elastic::Concerns::DatabaseReference` is included

To add data to the index, an instance of the new reference class is called in Elastic::ProcessBookkeepingService.track!() to add the data to a queue of references for indexing. A cron worker pulls queued references and bulk-indexes the items into Elasticsearch.

To test that the indexing operation works, call Elastic::ProcessBookkeepingService.track!() with an instance of the reference class and run The logs show the updates. To check the document in the index, run this command:

curl "http://localhost:9200/gitlab-development-<type>/_search"

Data consistency

Now that we have an index and a way to bulk index the new document type into Elasticsearch, we need to add data into the index. This consists of doing a backfill and doing continuous updates to ensure the index data is up to date.

The backfill is done by calling Elastic::ProcessInitialBookkeepingService.track!() with an instance of Search::Elastic::Reference for every document that should be indexed.

The continuous update is done by calling Elastic::ProcessBookkeepingService.track!() with an instance of Search::Elastic::Reference for every document that should be created/updated/deleted.

Backfilling data

Add a new Advanced Search migration to backfill data by executing scripts/elastic-migration and following the instructions.

The backfill should execute Elastic::ProcessInitialBookkeepingService.track!() with an instance of the Search::Elastic::Reference created before for every document that should be indexed. The BackfillEpics migration can be used as an example.

To test the backfill, run in a console a couple of times and see that the index was populated.

Tail the logs to see the progress of the migration:

tail -f log/elasticsearch.log

Continuous updates

For ActiveRecord objects, the ApplicationVersionedSearch concern can be included on the model to index data based on callbacks. If that’s not suitable, call Elastic::ProcessBookkeepingService.track!() with an instance of Search::Elastic::Reference whenever a document should be indexed.

Always check for Gitlab::CurrentSettings.elasticsearch_indexing? and use_elasticsearch? because some self-managed instances do not have Elasticsearch enabled and namespace limiting can be enabled.

Also check that the index is able to handle the index request. For example, check that the index exists if it was added in the current major release by verifying that the migration to add the index was completed: Elastic::DataMigrationService.migration_has_finished?.

Create the following MRs and have them reviewed by a member of the Global Search team:

  1. Create the index.
  2. Create a new Elasticsearch reference.
  3. Perform continuous updates behind a feature flag. Enable the flag fully before the backfill.
  4. Backfill the data.

After indexing is done, the index is ready for search.

Adding a new scope to search service

Search data is available in SearchController and Search API. Both use the SearchService to return results. The SearchService can be used to return results outside of the SearchController and Search API.

Search scopes

The SearchService exposes searching at global, group, and project levels.

New scopes must be added to the following constants:

  • ALLOWED_SCOPES (or override allowed_scopes method) in each EE SearchService file
  • ALLOWED_SCOPES in Gitlab::Search::AbuseDetection
  • search_tab_ability_map method in Search::Navigation. Override in the EE version if needed
Global search can be disabled for a scope. Create an ops feature flag named global_search_SCOPE_tab that defaults to true and add it to the global_search_enabled_for_scope? method in SearchService.

Results classes

The search results class available are:

Search type Search level Class
Basic search global Gitlab::SearchResults
Basic search group Gitlab::GroupSearchResults
Basic search project Gitlab::ProjectSearchResults
Advanced search global Gitlab::Elastic::SearchResults
Advanced search group Gitlab::Elastic::GroupSearchResults
Advanced search project Gitlab::Elastic::ProjectSearchResults
Exact code search global Search::Zoekt::SearchResults
Exact code search group Search::Zoekt::SearchResults
Exact code search project Search::Zoekt::SearchResults
All search types All levels Search::EmptySearchResults

The result class returns the following data:

  1. objects - paginated from Elasticsearch transformed into database records or POROs
  2. formatted_count - document count returned from Elasticsearch
  3. highlight_map - map of highlighted fields from Elasticsearch
  4. failed? - if a failure occurred
  5. error - error message returned from Elasticsearch
  6. aggregations - (optional) aggregations from Elasticsearch

New scopes must add support to these methods within Gitlab::Elastic::SearchResults class:

  • objects
  • formatted_count
  • highlight_map
  • failed?
  • error

Building a query

The query builder framework is used to build Elasticsearch queries.

A query is built using:

  • a query from Search::Elastic::Queries
  • one or more filters from ::Search::Elastic::Filters
  • (optional) aggregations from ::Search::Elastic::Aggregations
  • one or more formats from ::Search::Elastic::Formats

New scopes must create a new query builder class that inherits from Search::Elastic::QueryBuilder.

Sending queries to Elasticsearch

The queries are sent to ::Gitlab::Search::Client from Gitlab::Elastic::SearchResults. Results are parsed through a Search::Elastic::ResponseMapper to translate the response from Elasticsearch.

Model requirements

The model must response to the to_ability_name method so that the redaction logic can check if it has Ability.allowed?(current_user, :"read_#{object.to_ability_name}", object)?. The method must be added if it does not exist.

The model must define a preload_search_data scope to avoid N+1s.

Permissions tests

Search code has a final security check in SearchService#redact_unauthorized_results. This prevents unauthorized results from being returned to users who don’t have permission to view them. The check is done in Ruby to handle inconsistencies in Elasticsearch permissions data due to bugs or indexing delays.

New scopes must add visibility specs to ensure proper access control. To test that permissions are properly enforced, add tests using the 'search respects visibility' shared example in the EE specs:

  • ee/spec/services/search/global_service_spec.rb
  • ee/spec/services/search/group_service_spec.rb
  • ee/spec/services/search/project_service_spec.rb

Testing the new scope

Test your new scope in the Rails console

search_service =, { search: 'foo', scope: 'SCOPE_NAME' })

Create the following MRs and have them reviewed by a member of the Global Search team:

  1. Enable the new scope.
  2. Create a query builder.
  3. Implement all model requirements.
  4. Add the new scope to Gitlab::Elastic::SearchResults behind a feature flag.
  5. Add specs which must include permissions tests
  6. Test the new scope
  7. Update documentation for Advanced search and Search API (if applicable)

Zero-downtime reindexing with multiple indices

This is not applicable yet as multiple indices functionality is not fully implemented.

Currently GitLab can only handle a single version of setting. Any setting/schema changes would require reindexing everything from scratch. Since reindexing can take a long time, this can cause search functionality downtime.

To avoid downtime, GitLab is working to support multiple indices that can function at the same time. Whenever the schema changes, the administrator will be able to create a new index and reindex to it, while searches continue to go to the older, stable index. Any data updates will be forwarded to both indices. Once the new index is ready, an administrator can mark it active, which will direct all searches to it, and remove the old index.

This is also helpful for migrating to new servers, for example, moving to/from AWS.

Currently we are on the process of migrating to this new design. Everything is hardwired to work with one single version for now.


The traditional setup, provided by elasticsearch-rails, is to communicate through its internal proxy classes. Developers would write model-specific logic in a module for the model to include in (for example, SnippetsSearch). The __elasticsearch__ methods would return a proxy object, for example:

  • Issue.__elasticsearch__ returns an instance of Elasticsearch::Model::Proxy::ClassMethodsProxy
  • Issue.first.__elasticsearch__ returns an instance of Elasticsearch::Model::Proxy::InstanceMethodsProxy.

These proxy objects would talk to Elasticsearch server directly (see top half of the diagram).

Elasticsearch Architecture

In the planned new design, each model would have a pair of corresponding sub-classed proxy objects, in which model-specific logic is located. For example, Snippet would have SnippetClassProxy being a subclass of Elasticsearch::Model::Proxy::ClassMethodsProxy. Snippet would have SnippetInstanceProxy being a subclass of Elasticsearch::Model::Proxy::InstanceMethodsProxy.

__elasticsearch__ would represent another layer of proxy object, keeping track of multiple actual proxy objects. It would forward method calls to the appropriate index. For example:

  • would be forwarded to the one stable index, since it is a read operation.
  • model.__elasticsearch__.update_document would be forwarded to all indices, to keep all indices up-to-date.

The global configurations per version are now in the Elastic::(Version)::Config class. You can change mappings there.

Creating new version of schema

This is not applicable yet as multiple indices functionality is not fully implemented.

Folders like ee/lib/elastic/v12p1 contain snapshots of search logic from different versions. To keep a continuous Git history, the latest version lives under ee/lib/elastic/latest, but its classes are aliased under an actual version (for example, ee/lib/elastic/v12p3). When referencing these classes, never use the Latest namespace directly, but use the actual version (for example, V12p3).

The version name basically follows the GitLab release version. If setting is changed in 12.3, we will create a new namespace called V12p3 (p stands for “point”). Raise an issue if there is a need to name a version differently.

If the current version is v12p1, and we need to create a new version for v12p3, the steps are as follows:

  1. Copy the entire folder of v12p1 as v12p3
  2. Change the namespace for files under v12p3 folder from V12p1 to V12p3 (which are still aliased to Latest)
  3. Delete v12p1 folder
  4. Copy the entire folder of latest as v12p1
  5. Change the namespace for files under v12p1 folder from Latest to V12p1
  6. Make changes to files under the latest folder as needed

Performance Monitoring


GitLab exports Prometheus metrics relating to the number of requests and timing for all web/API requests and Sidekiq jobs, which can help diagnose performance trends and compare how Elasticsearch timing is impacting overall performance relative to the time spent doing other things.

Indexing queues

GitLab also exports Prometheus metrics for indexing queues, which can help diagnose performance bottlenecks and determine whether or not your GitLab instance or Elasticsearch server can keep up with the volume of updates.


All of the indexing happens in Sidekiq, so much of the relevant logs for the Elasticsearch integration can be found in sidekiq.log. In particular, all Sidekiq workers that make requests to Elasticsearch in any way will log the number of requests and time taken querying/writing to Elasticsearch. This can be useful to understand whether or not your cluster is keeping up with indexing.

Searching Elasticsearch is done via ordinary web workers handling requests. Any requests to load a page or make an API request, which then make requests to Elasticsearch, will log the number of requests and the time taken to production_json.log. These logs will also include the time spent on Database and Gitaly requests, which may help to diagnose which part of the search is performing poorly.

There are additional logs specific to Elasticsearch that are sent to elasticsearch.log that may contain information to help diagnose performance issues.

Performance Bar

Elasticsearch requests will be displayed in the Performance Bar, which can be used both locally in development and on any deployed GitLab instance to diagnose poor search performance. This will show the exact queries being made, which is useful to diagnose why a search might be slow.

Correlation ID and X-Opaque-Id

Our correlation ID is forwarded by all requests from Rails to Elasticsearch as the X-Opaque-Id header which allows us to track any tasks in the cluster back the request in GitLab.


Getting flood stage disk watermark [95%] exceeded

You might get an error such as

[2018-10-31T15:54:19,762][WARN ][o.e.c.r.a.DiskThresholdMonitor] [pval5Ct]
   flood stage disk watermark [95%] exceeded on
   [pval5Ct7SieH90t5MykM5w][pval5Ct][/usr/local/var/lib/elasticsearch/nodes/0] free: 56.2gb[3%],
   all indices on this node will be marked read-only

This is because you’ve exceeded the disk space threshold - it thinks you don’t have enough disk space left, based on the default 95% threshold.

In addition, the read_only_allow_delete setting will be set to true. It will block indexing, forcemerge, etc

curl "http://localhost:9200/gitlab-development/_settings?pretty"

Add this to your elasticsearch.yml file:

# turn off the disk allocator
cluster.routing.allocation.disk.threshold_enabled: false


# set your own limits
cluster.routing.allocation.disk.threshold_enabled: true
cluster.routing.allocation.disk.watermark.flood_stage: 5gb   # ES 6.x only
cluster.routing.allocation.disk.watermark.low: 15gb
cluster.routing.allocation.disk.watermark.high: 10gb

Restart Elasticsearch, and the read_only_allow_delete will clear on its own.

_from “Disk-based Shard Allocation Elasticsearch Reference” 5.6 and 6.x_

Disaster recovery/data loss/backups

The use of Elasticsearch in GitLab is only ever as a secondary data store. This means that all of the data stored in Elasticsearch can always be derived again from other data sources, specifically PostgreSQL and Gitaly. Therefore if the Elasticsearch data store is ever corrupted for whatever reason you can reindex everything from scratch.

If your Elasticsearch index is incredibly large it may be too time consuming or cause too much downtime to reindex from scratch. There aren’t any built in mechanisms for automatically finding discrepancies and resyncing an Elasticsearch index if it gets out of sync but one tool that may be useful is looking at the logs for all the updates that occurred in a time range you believe may have been missed. This information is very low level and only useful for operators that are familiar with the GitLab codebase. It is documented here in case it is useful for others. The relevant logs that could theoretically be used to figure out what needs to be replayed are:

  1. All non-repository updates that were synced can be found in elasticsearch.log by searching for track_items and these can be replayed by sending these items again through ::Elastic::ProcessBookkeepingService.track!
  2. All repository updates that occurred can be found in elasticsearch.log by searching for indexing_commit_range. Replaying these requires resetting the IndexStatus#last_commit/last_wiki_commit to the oldest from_sha in the logs and then triggering another index of the project using ElasticCommitIndexerWorker
  3. All project deletes that occurred can be found in sidekiq.log by searching for ElasticDeleteProjectWorker. These updates can be replayed by triggering another ElasticDeleteProjectWorker.

With the above methods and taking regular Elasticsearch snapshots we should be able to recover from different kinds of data loss issues in a relatively short period of time compared to indexing everything from scratch.