The site that you are currently viewing is a static version of the Software Factory documentation delivered with the

version v7.2.
For up-to-date documentation, see the latest version.

GitLab Advanced Search

How to enable GitLab Advanced Search

Overview

This page explains how to enable advanced search. Once activated, advanced search offers faster results and enhanced search capabilities.

Warning

Prior to enabling this feature, please be aware that Elasticsearch require more resources than GitLab installation requirements and review the official GitLab system requirements for Elasticsearch thoroughly.

To enable advanced search, you must:

  1. Install an Elasticsearch .
  2. Enable advanced search .
Note

Advanced search stores all projects in the same Elasticsearch indices. However, private projects are only visible in search results to users with the appropriate access rights.

Install an Elasticsearch cluster

Elasticsearch and any OpenSearch variants are not included in the SWaaP package.

You can install a search cluster yourself or use a cloud-hosted offering.

You should install the search cluster on a separate server. Running the search cluster on the same server as GitLab might lead to performance issues.

For a search cluster with a single node, the cluster status is always yellow because the primary shard is allocated. The cluster cannot assign replica shards to the same node as primary shards.

Note

Before using a new Elasticsearch cluster in production, you should review the important Elasticsearch settings .

Version requirements

Elasticsearch

Note
  • Support for Elasticsearch 6.8 removed in GitLab 15.0.

Advanced search works with the following versions of Elasticsearch.

GitLab versionElasticsearch version
GitLab 18.1 and laterElasticsearch 7.x and later
GitLab 15.0 to 18.0Elasticsearch 7.x and 8.x
GitLab 14.0 to 14.10Elasticsearch 6.8 to 7.x

Advanced search follows the Elasticsearch end-of-life policy .

If your version of Elasticsearch is incompatible, to prevent data loss, indexing pauses and a message is logged in the GitLab UI.

System requirements

Elasticsearch requires more resources than GitLab installation requirements. Memory, CPU, and storage requirements depend on the amount of data you index. Heavily used Elasticsearch clusters might require more resources. The estimate_cluster_size Rake task uses the total repository size to estimate the advanced search storage requirements.

Prerequisites:

To enable advanced search:

  1. On the left sidebar, at the bottom, select Admin.
  2. Select Settings > Search.
  3. Configure the advanced search settings for your Elasticsearch cluster. Do not select the Search with Elasticsearch enabled checkbox yet.
  4. Index the instance .
  5. Optional. Check indexing status .
  6. After the indexing is complete, select the Search with Elasticsearch enabled checkbox, then select Save changes.
Warning

When your Elasticsearch cluster is down while Elasticsearch is enabled, you might have problems updating documents such as issues because your instance queues a job to index the change, but cannot find a valid Elasticsearch cluster.

For GitLab instances with more than 50 GB of repository data, see Index large instances efficiently .

Index the instance

From the user interface

Note

Introduced in GitLab 17.3.

Prerequisites:

  • You must have administrator access to the instance

You can perform initial indexing or re-create an index from the user interface. To enable advanced search and index the instance from the user interface:

  1. On the left sidebar, at the bottom, select Admin.
  2. Select Settings > Search.
  3. Select the Elasticsearch indexing checkbox, then select Save changes.
  4. Select Index the instance.

Check indexing status

Prerequisites:

  • You must have administrator access to the instance.

To check indexing status:

  1. On the left sidebar, at the bottom, select Admin.
  2. Select Settings > Search.
  3. Expand Indexing status.

Monitor the status of background jobs

Prerequisites:

  • You must have administrator access to the instance.

To monitor the status of background jobs:

  1. On the left sidebar, at the bottom, select Admin.
  2. Select Monitoring > Background jobs.
  3. On the Sidekiq dashboard, select Busy and wait for all of the indexing jobs to complete. These jobs index code and wiki data for projects and groups.

Prerequisites:

  • You must have administrator access to the instance.

To enable search with advanced search in GitLab:

  1. On the left sidebar, at the bottom, select Admin.
  2. Select Settings > Search.
  3. Select the Search with Elasticsearch enabled checkbox.
  4. Select Save changes.

Advanced search configuration

The following Elasticsearch settings are available:

ParameterDescription
Elasticsearch indexingEnables or disables Elasticsearch indexing and creates an empty index if one does not already exist. You may want to enable indexing but disable search to give the index time to be fully completed, for example. Also, keep in mind that this option doesn’t have any impact on existing data, this only enables/disables the background indexer which tracks data changes and ensures new data is indexed.
Pause Elasticsearch indexingEnables or disables temporary indexing pause. This is useful for cluster migration/reindexing. All changes are still tracked, but they are not committed to the Elasticsearch index until resumed.
Search with Elasticsearch enabledEnables or disables using Elasticsearch in search.
Requeue indexing workersEnable automatic requeuing of indexing workers. This improves non-code indexing throughput by enqueuing Sidekiq jobs until all documents are processed. Requeuing indexing workers is not recommended for smaller instances or instances with few Sidekiq processes.
URLThe URL of your Elasticsearch instance. Use a comma-separated list to support clustering (for example, http://host1, https://host2:9200). If your Elasticsearch instance is password-protected, use the Username and Password fields. Alternatively, use inline credentials such as http://<username>:<password>@<elastic_host>:9200/. If you use OpenSearch , only connections over ports 80 and 443 are accepted.
UsernameThe username of your Elasticsearch instance.
PasswordThe password of your Elasticsearch instance.
Number of Elasticsearch shards and replicas per indexElasticsearch indices are split into multiple shards for performance reasons. In general, you should use at least five shards. Indices with tens of millions of documents should have more shards (see the guidance ). Changes to this value do not take effect until you re-create the index. For more information about scalability and resilience, see the Elasticsearch documentation . Each Elasticsearch shard can have a number of replicas. These replicas are a complete copy of the shard and can provide increased query performance or resilience against hardware failure. Increasing this value increases the total disk space required by the index. You can set the number of shards and replicas for each of the indices.
Limit the amount of namespace and project data to indexWhen you enable this setting, you can specify namespaces and projects to index. All other namespaces and projects use database search instead. If you enable this setting but do not specify any namespace or project, only project records are indexed. For more information, see Limit the amount of namespace and project data to index .
Use AWS OpenSearch Service with IAM credentialsSign your OpenSearch requests using AWS IAM authorization , AWS EC2 Instance Profile Credentials , or AWS ECS Tasks Credentials . Refer to Identity and Access Management in Amazon OpenSearch Service for details of AWS hosted OpenSearch domain access policy configuration.
AWS RegionThe AWS region in which your OpenSearch Service is located.
AWS Access KeyThe AWS access key.
AWS Secret Access KeyThe AWS secret access key.
Maximum file size indexedSee the explanation in instance limits
Maximum field lengthSee the explanation in instance limits
Number of shards for non-code indexingNumber of indexing worker shards. This improves non-code indexing throughput by enqueuing more parallel Sidekiq jobs. Increasing the number of shards is not recommended for smaller instances or instances with few Sidekiq processes. Default is 2.
Maximum bulk request size (MiB)Used by the GitLab Ruby and Go-based indexer processes. This setting indicates how much data must be collected (and stored in memory) in a given indexing process before submitting the payload to the Elasticsearch Bulk API. For the GitLab Go-based indexer, you should use this setting with Bulk request concurrency. Maximum bulk request size (MiB) must accommodate the resource constraints of both the Elasticsearch hosts and the hosts running the GitLab Go-based indexer from either the gitlab-rake command or the Sidekiq tasks.
Bulk request concurrencyThe Bulk request concurrency indicates how many of the GitLab Go-based indexer processes (or threads) can run in parallel to collect data to subsequently submit to the Elasticsearch Bulk API. This increases indexing performance, but fills the Elasticsearch bulk requests queue faster. This setting should be used together with the Maximum bulk request size setting and needs to accommodate the resource constraints of both the Elasticsearch hosts and the hosts running the GitLab Go-based indexer either from the gitlab-rake command or the Sidekiq tasks.
Client request timeoutElasticsearch HTTP client request timeout value in seconds. 0 means using the system default timeout value, which depends on the libraries that GitLab application is built upon.
Code indexing concurrencyMaximum number of Elasticsearch code indexing background jobs allowed to run concurrently. This only applies to repository indexing operations.
Retry on failureMaximum number of possible retries for Elasticsearch search requests. Introduced in GitLab 17.6.
Index prefixCustom prefix for Elasticsearch index names. Defaults to gitlab. When changed, all indices will use this prefix instead of gitlab (for example, custom-production-issues instead of gitlab-production-issues). Must be 1-100 characters, contain only lowercase alphanumeric characters, hyphens, and underscores, and cannot start or end with a hyphen or underscore. Introduced in GitLab 18.2.
Warning

Increasing the values of Maximum bulk request size (MiB) and Bulk request concurrency can negatively impact Sidekiq performance. Return them to their default values if you see increased scheduling_latency_s durations in your Sidekiq logs. For more information, see issue 322147 .

Limit the amount of namespace and project data to index

Note
  • Indexing all project records introduced in GitLab 16.7 with a flag named search_index_all_projects. Disabled by default.
  • Generally available in GitLab 16.11. Feature flag search_index_all_projects removed.
  • Indexing vulnerability records introduced on GitLab.com and GitLab Dedicated in GitLab 18.1 with a flag named vulnerability_es_ingestion. Disabled by default.
  • Indexing vulnerability records is generally available on GitLab.com and GitLab Dedicated in GitLab 18.2. Feature flag vulnerability_es_ingestion removed.
Warning

The availability of this feature is controlled by a feature flag. For more information, see the history.

When you select the Limit the amount of namespace and project data to index checkbox, you can specify namespaces and projects to index. If the namespace is a group, any subgroups and projects in these subgroups are also indexed.

When you enable this setting:

  • Namespaces or projects must be specified for full indexing.
  • Project records (metadata like project names and descriptions) are always indexed for all projects.
  • Vulnerability records are always indexed for all projects and namespaces to support filtering in security reports.
  • Associated data is indexed only for the namespaces and projects you specify.
Warning

If you do not specify any namespace or project after you enable this setting, only project records are indexed and no associated data can be searched.

Indexed namespaces

Note
  • Global search for limited indexing introduced in GitLab 13.4 [with a flag named advanced_global_search_for_limited_indexing. Disabled by default.
  • Enabled on GitLab.com in GitLab 14.2.
  • Global search for limited indexing generally available in GitLab 17.11 as a UI option, instead of the advanced_global_search_for_limited_indexing flag.

When you index all namespaces, you can use advanced search for global code and commit search. When you index only some namespaces:

  • Global search does not include a code or commit search scope.
  • Code and commit searches are available only in a single indexed namespace.
  • A single code or commit search is not possible across multiple indexed namespaces.
  • Cross-project search is available in an indexed namespace.

For example, if you index two separate groups, you must run separate code searches on each group individually.

To enable global search for limited indexing:

  1. On the left sidebar, at the bottom, select Admin.
  2. Select Settings > Search.
  3. Expand Advanced search
  4. Select Enable global search for limited indexing.
  5. Select Save changes.
  6. If you’ve already indexed your instance, you must reindex the instance . This deletes existing search data, to enable filtering to work correctly.

Prerequisites:

  • You must have administrator access to the instance.

To disable advanced search in GitLab:

  1. On the left sidebar, at the bottom, select Admin.

  2. Select Settings > Search.

  3. Clear the Elasticsearch indexing and Search with Elasticsearch enabled checkboxes.

  4. Select Save changes.

  5. Optional. For Elasticsearch instances that are still online, delete existing indices - as cluster admin, open a bash shell on the toolbox pod inside the GitLab namespace:

    kubectl -n gitlab get pod | grep toolbox
    kubectl -n gitlab exec -it gitlab-toolbox-<pod-id> -- bash
    

    Then run the gitlab-rake command:

    gitlab-rake gitlab:elastic:delete_index
    

Prerequisites:

  • You must have administrator access to the instance.

To disable search with advanced search in GitLab:

  1. On the left sidebar, at the bottom, select Admin.
  2. Select Settings > Search.
  3. Clear the Search with Elasticsearch enabled checkbox.
  4. Select Save changes.

Pause indexing

Prerequisites:

  • You must have administrator access to the instance.

To pause indexing:

  1. On the left sidebar, at the bottom, select Admin.
  2. Select Settings > Search.
  3. Expand Advanced Search.
  4. Select the Pause Elasticsearch indexing checkbox.
  5. Select Save changes.

Resume indexing

Prerequisites:

  • You must have administrator access to the instance.

To resume indexing:

  1. On the left sidebar, at the bottom, select Admin.
  2. Select Settings > Search.
  3. Expand Advanced Search.
  4. Clear the Pause Elasticsearch indexing checkbox.
  5. Select Save changes.

Zero-downtime reindexing

The idea behind this reindexing method is to leverage the Elasticsearch reindex API and Elasticsearch index alias feature to perform the operation. We set up an index alias which connects to a primary index which is used by GitLab for reads/writes. When reindexing process starts, we temporarily pause the writes to the primary index. Then, we create another index and invoke the Reindex API which migrates the index data onto the new index. After the reindexing job is complete, we switch to the new index by connecting the index alias to it which becomes the new primary index. At the end, we resume the writes and typical operation resumes.

Using zero-downtime reindexing

You can use zero-downtime reindexing to configure index settings or mappings that cannot be changed without creating a new index and copying existing data. You should not use zero-downtime reindexing to fix missing data. Zero-downtime reindexing does not add data to the search cluster if the data is not already indexed. You must complete all advanced search migrations before you start reindexing.

Trigger reindexing

Prerequisites:

  • You must have administrator access to the instance.

To trigger reindexing:

  1. Sign in to your GitLab instance as an administrator.
  2. On the left sidebar, at the bottom, select Admin.
  3. Select Settings > Search.
  4. Expand Elasticsearch zero-downtime reindexing.
  5. Select Trigger cluster reindexing.

Reindexing can be a lengthy process depending on the size of your Elasticsearch cluster.

After this process is completed, the original index is scheduled to be deleted after 14 days. You can cancel this action by pressing the Cancel button on the same page you triggered the reindexing process.

While the reindexing is running, you can follow its progress under that same section.

Trigger zero-downtime reindexing

Prerequisites:

  • You must have administrator access to the instance.

To trigger zero-downtime reindexing:

  1. On the left sidebar, at the bottom, select Admin.

  2. Select Settings > Search.

  3. Expand Elasticsearch zero-downtime reindexing. The following settings are available:

Slice multiplier

The slice multiplier calculates the number of slices during reindexing .

GitLab uses manual slicing to control the reindex efficiently and safely, which enables users to retry only failed slices.

The multiplier defaults to 2 and applies to the number of shards per index. For example, if this value is 2 and your index has 20 shards, then the reindex task is split into 40 slices.

Maximum running slices

The maximum running slices parameter defaults to 60 and corresponds to the maximum number of slices allowed to run concurrently during Elasticsearch reindexing.

Setting this value too high can have adverse performance impacts as your cluster may become heavily saturated with searches and writes. Setting this value too low may lead the reindexing process to take a very long time to complete.

The best value for this depends on your cluster size, whether you’re willing to accept some degraded search performance during reindexing, and how important it is for the reindex to finish quickly and resume indexing.

Mark the most recent reindexing job as failed and resume indexing

Prerequisites:

  • You must have administrator access to the instance.

To abandon an unfinished reindexing job and resume indexing:

  1. Mark the most recent reindexing job as failed:

    # For installations that use the Linux package
    sudo gitlab-rake gitlab:elastic:mark_reindex_failed
    
    # For self-compiled installations
    bundle exec rake gitlab:elastic:mark_reindex_failed RAILS_ENV=production
    
  2. On the left sidebar, at the bottom, select Admin.

  3. Select Settings > Search.

  4. Expand Advanced Search.

  5. Clear the Pause Elasticsearch indexing checkbox.

Index integrity

Note
  • Introduced in GitLab 15.10 with a flag named search_index_integrity. Disabled by default.
  • Generally available in GitLab 16.4. Feature flag search_index_integrity removed.

Index integrity detects and fixes missing repository data. This feature is automatically used when code searches scoped to a group or project return no results.

Advanced search migrations

Reindex migrations run in the background, which means you do not have to reindex the instance manually.

In GitLab 18.0 and later , you can use the elastic_migration_worker_enabled application setting to enable or disable the migration worker. By default, the migration worker is enabled.

Migration dictionary files

Note

Every migration has a corresponding dictionary file in the ee/elastic/docs/ folder with the following information:

name:
version:
description:
group:
milestone:
introduced_by_url:
obsolete:
marked_obsolete_by_url:
marked_obsolete_in_milestone:

You can use this information, for example, to identify when a migration was introduced or was marked as obsolete.

Check for pending migrations

To check for pending advanced search migrations, run this command:

curl "$CLUSTER_URL/gitlab-production-migrations/_search?size=100&q=*" | jq .

This should return something similar to:

{
  "took": 14,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 1,
    "hits": [
      {
        "_index": "gitlab-production-migrations",
        "_type": "_doc",
        "_id": "20230209195404",
        "_score": 1,
        "_source": {
          "completed": true
        }
      }
    ]
  }
}

To debug issues with the migrations, check the elasticsearch.log

Retry a halted migration

Some migrations are built with a retry limit. If the migration cannot finish within the retry limit, it is halted and a notification is displayed in the advanced search integration settings.

It is recommended to check the elasticsearch.log file to debug why the migration was halted and make any changes before retrying the migration.

When you believe you’ve fixed the cause of the failure:

  1. On the left sidebar, at the bottom, select Admin.
  2. Select Settings > Search.
  3. Expand Advanced Search.
  4. Inside the Elasticsearch migration halted alert box, select Retry migration. The migration is scheduled to be retried in the background.

If you cannot get the migration to succeed, you may consider the last resort to recreate the index from scratch. This may allow you to skip over the problem because a newly created index skips all migrations as the index is recreated with the correct up-to-date schema.

All migrations must be finished before doing a major upgrade

Before upgrading to a major GitLab version, you must complete all migrations that exist up until the latest minor version before that major version. You must also resolve and retry any halted migrations before proceeding with a major version upgrade.

Migrations that have been removed are marked as obsolete . If you upgrade GitLab before all pending advanced search migrations are completed, any pending migrations that have been removed in the new version cannot be executed or retried. In this case, you must re-create your index from scratch.

Skippable migrations

Skippable migrations are only executed when a condition is met. For example, if a migration depends on a specific version of Elasticsearch, it could be skipped until that version is reached.

If a skippable migration is not executed by the time the migration is marked as obsolete, to apply the change you must re-create the index.

Estimate cluster size

Get an estimate of code and wiki index sizes and total cluster size based on the total repository size.

 sudo gitlab-rake gitlab:elastic:estimate_cluster_size`

Example output:

This GitLab instance repository size is 1.8 GiB and wiki size is 0 B.
The gitlab-production index size will be 913.5 MiB and gitlab-production-wikis index size will be 0 B.
By our estimates, your cluster size will be at least 913.5 MiB.
Please note that it is possible to index only selected namespaces/projects by using Advanced search indexing restrictions.

Indexing a range of projects or a specific project

Using the ID_FROM and ID_TO environment variables, you can index a limited number of projects. This can be useful for staging indexing.

root@git:~# sudo gitlab-rake gitlab:elastic:index_projects ID_FROM=1 ID_TO=100

Because ID_FROM and ID_TO use the or equal to comparison, you can use them to index only one project by setting both to the same project ID:

root@git:~# sudo gitlab-rake gitlab:elastic:index_projects ID_FROM=5 ID_TO=5
Indexing project repositories...I, [2019-03-04T21:27:03.083410 #3384]  INFO -- : Indexing GitLab User / test (ID=33)...
I, [2019-03-04T21:27:05.215266 #3384]  INFO -- : Indexing GitLab User / test (ID=33) is done!

Advanced search index scopes

When performing a search, the GitLab index uses the following scopes:

Scope NameWhat it searches
commitsCommit data
projectsProject data (default)
blobsCode
issuesIssue data
merge_requestsMerge request data
milestonesMilestone data
notesNote data
snippetsSnippet data
wiki_blobsWiki contents
usersUsers
epicsEpic data

On GitLab.com and GitLab Dedicated, vulnerability records are always indexed for all projects and namespaces to support features outside of search. Indexing vulnerability records on GitLab Self-Managed is proposed in issue 525484 .

Tuning

Guidance on choosing optimal cluster configuration

For basic guidance on choosing a cluster configuration, see also Elastic Cloud Calculator .

  • Generally, you want to use at least a 2-node cluster configuration with one replica, which allows you to have resilience. If your storage usage is growing quickly, you may want to plan horizontal scaling (adding more nodes) beforehand.
  • It’s not recommended to use HDD storage with the search cluster, because it takes a hit on performance. It’s better to use SSD storage (NVMe or SATA SSD drives for example).
  • You should not use coordinating-only nodes with large instances. Coordinating-only nodes are smaller than data nodes , which can impact performance and advanced search migrations .
  • You can use the GitLab Performance Tool to benchmark search performance with different search cluster sizes and configurations.
  • Heap size should be set to no more than 50% of your physical RAM. Additionally, it shouldn’t be set to more than the threshold for zero-based compressed oops. The exact threshold varies, but 26 GB is safe on most systems, but can also be as large as 30 GB on some systems. See Heap size settings and Setting JVM options for more details.
  • refresh_interval is a per index setting. You may want to adjust that from default 1s to a bigger value if you don’t need data in real-time. This changes how soon you see fresh results. If that’s important for you, you should leave it as close as possible to the default value.
  • You might want to raise indices.memory.index_buffer_size to 30% or 40% if you have a lot of heavy indexing operations.

Advanced search settings

Number of Elasticsearch shards

Note
  • gitlab:elastic:estimate_shard_sizes introduced in GitLab 16.11.
  • gitlab:elastic:estimate_shard_sizes changed in GitLab 18.3 to include sizing for indices that contain repository data.

For single-node clusters, set the number of Elasticsearch shards per index to the number of CPU cores on the Elasticsearch data nodes.

For multi-node clusters, run the Rake task gitlab:elastic:estimate_shard_sizes to determine the number of shards for each index. The task returns recommendations for shard and replica sizes and approximate document counts for indices that contain database data.

Keep the average shard size between a few GB and 30 GB. If the average shard size grows to more than 30 GB, increase the shard size for the index and trigger zero-downtime reindexing . To ensure the cluster is healthy, the number of shards per node must not exceed 20 times the configured heap size. For example, a node with a 30 GB heap must have a maximum of 600 shards.

To update the number of shards for an index, change the setting and trigger zero-downtime reindexing .

Number of Elasticsearch replicas

For single-node clusters, set the number of Elasticsearch replicas per index to 0.

For multi-node clusters, set the number of Elasticsearch replicas per index to 1 (each shard has one replica). The number must not be 0 because losing one node corrupts the index.

If shard allocation awareness is enabled, the total number of copies per shard must be evenly divisible by the number of awareness attributes (typically nodes or zones). The even distribution of shard copies across all awareness attributes ensures optimal fault tolerance and load distribution.

(1 + `number_of_replicas`) / `number_of_awareness_attributes` = whole number

To update the number of replicas for an index, change the setting and trigger zero-downtime reindexing .

Index large instances efficiently

Prerequisites:

  • You must have administrator access to the instance.
Warning

Indexing a large instance generates a lot of Sidekiq jobs. Make sure to prepare for this task by having a scalable setup or by creating extra Sidekiq processes.

If enabling advanced search causes problems due to large volumes of data being indexed:

  1. Configure your Elasticsearch host and port .

  2. Create empty indices:

    # For installations that use the Linux package
    sudo gitlab-rake gitlab:elastic:create_empty_index
    
    # For self-compiled installations
    bundle exec rake gitlab:elastic:create_empty_index RAILS_ENV=production
    
  3. If this is a reindex of your GitLab instance, clear the index status:

    # For installations that use the Linux package
    sudo gitlab-rake gitlab:elastic:clear_index_status
    
    # For self-compiled installations
    bundle exec rake gitlab:elastic:clear_index_status RAILS_ENV=production
    
  4. Select the Elasticsearch indexing checkbox .

  5. Indexing large Git repositories can take a while. To speed up the process, you can tune for indexing speed :

    • You can temporarily increase refresh_interval .

    • You can set the number of replicas to 0. This setting controls the number of copies each primary shard of an index has. Thus, having 0 replicas effectively disables the replication of shards across nodes, which should increase the indexing performance. This is an important trade-off in terms of reliability and query performance. It is important to remember to set the replicas to a considered value after the initial indexing is complete.

    You can expect a 20% decrease in indexing time. After the indexing is complete, you can set refresh_interval and number_of_replicas back to their desired values.

Warning

This step is optional but may help significantly speed up large indexing operations.

curl --request PUT localhost:9200/gitlab-production/_settings --header 'Content-Type: application/json' \
     --data '{
       "index" : {
           "refresh_interval" : "30s",
           "number_of_replicas" : 0
       } }'
  1. Index projects and their associated data:

    # For installations that use the Linux package
    sudo gitlab-rake gitlab:elastic:index_projects
    
    # For self-compiled installations
    bundle exec rake gitlab:elastic:index_projects RAILS_ENV=production
    

    This enqueues a Sidekiq job for each project that needs to be indexed. You can view the jobs in the Admin area under Monitoring > Background jobs > Queues Tab and select elastic_commit_indexer, or you can query indexing status using a Rake task:

    # For installations that use the Linux package
    sudo gitlab-rake gitlab:elastic:index_projects_status
    
    # For self-compiled installations
    bundle exec rake gitlab:elastic:index_projects_status RAILS_ENV=production
    
    Indexing is 65.55% complete (6555/10000 projects)
    

    If you want to limit the index to a range of projects you can provide the ID_FROM and ID_TO parameters:

    # For installations that use the Linux package
    sudo gitlab-rake gitlab:elastic:index_projects ID_FROM=1001 ID_TO=2000
    
    # For self-compiled installations
    bundle exec rake gitlab:elastic:index_projects ID_FROM=1001 ID_TO=2000 RAILS_ENV=production
    

    Where ID_FROM and ID_TO are project IDs. Both parameters are optional. The previous example indexes all projects from ID 1001 up to (and including) ID 2000.

    You can also use the gitlab:elastic:clear_index_status Rake task to force the indexer to “forget” all progress, so it retries the indexing process from the start.

  2. Epics, group wikis, personal snippets, and users are not associated with a project and must be indexed separately:

    # For installations that use the Linux package
    sudo gitlab-rake gitlab:elastic:index_epics
    sudo gitlab-rake gitlab:elastic:index_group_wikis
    sudo gitlab-rake gitlab:elastic:index_snippets
    sudo gitlab-rake gitlab:elastic:index_users
    
    # For self-compiled installations
    bundle exec rake gitlab:elastic:index_epics RAILS_ENV=production
    bundle exec rake gitlab:elastic:index_group_wikis RAILS_ENV=production
    bundle exec rake gitlab:elastic:index_snippets RAILS_ENV=production
    bundle exec rake gitlab:elastic:index_users RAILS_ENV=production
    
  3. Enable replication and refreshing again after indexing (only if you previously increased refresh_interval):

    curl --request PUT localhost:9200/gitlab-production/_settings --header 'Content-Type: application/json' \
         --data '{
           "index" : {
               "number_of_replicas" : 1,
               "refresh_interval" : "1s"
           } }'
    

    A force merge should be called after enabling refreshing.

    For Elasticsearch 6.x and later, ensure the index is in read-only mode before proceeding with the force merge:

    curl --request PUT localhost:9200/gitlab-production/_settings --header 'Content-Type: application/json' \
         --data '{
           "settings": {
             "index.blocks.write": true
           } }'
    

    Then, initiate the force merge:

    curl --request POST 'localhost:9200/gitlab-production/_forcemerge?max_num_segments=5'
    

    Then, change the index back to read-write mode:

    curl --request PUT localhost:9200/gitlab-production/_settings --header 'Content-Type: application/json' \
         --data '{
           "settings": {
             "index.blocks.write": false
           } }'
    
  4. After the indexing is complete, select the Search with Elasticsearch enabled checkbox .

Deleted documents

Whenever a change or deletion is made to an indexed GitLab object (a merge request description is changed, a file is deleted from the default branch in a repository, a project is deleted, etc), a document in the index is deleted. However, because these are “soft” deletes, the overall number of “deleted documents”, and therefore wasted space, increases.

Elasticsearch does intelligent merging of segments to remove these deleted documents. However, depending on the amount and type of activity in your GitLab installation, it’s possible to see as much as 50% of wasted space in the index.

In general, we recommend letting Elasticsearch merge and reclaim space automatically, with the default settings.

However, some larger installations may wish to tune the merge policy settings:

  • Consider reducing the index.merge.policy.max_merged_segment size from the default 5 GB to maybe 2 GB or 3 GB. Merging only happens when a segment has at least 50% deletions. Smaller segment sizes allows merging to happen more frequently.

    curl --request PUT localhost:9200/gitlab-production/_settings ---header 'Content-Type: application/json' \
         --data '{
           "index" : {
             "merge.policy.max_merged_segment": "2gb"
           }
         }'
    
  • You can also adjust index.merge.policy.reclaim_deletes_weight, which controls how aggressively deletions are targeted. But this can lead to costly merge decisions, so we recommend not changing this unless you understand the tradeoffs.

    curl --request PUT localhost:9200/gitlab-production/_settings ---header 'Content-Type: application/json' \
         --data '{
           "index" : {
             "merge.policy.reclaim_deletes_weight": "3.0"
           }
         }'
    
  • Do not do a force merge to remove deleted documents. A warning in the documentation states that this can lead to very large segments that may never get reclaimed, and can also cause significant performance or availability issues.

Index large instances with dedicated Sidekiq nodes or processes

Warning

For most instances, you do not have to configure dedicated Sidekiq nodes or processes. The following steps use an advanced setting of Sidekiq called routing rules. Be sure to fully understand about the implication of using routing rules to avoid losing jobs entirely.

Indexing a large instance can be a lengthy and resource-intensive process that has the potential of overwhelming Sidekiq nodes and processes. This negatively affects the GitLab performance and availability.

As GitLab allows you to start multiple Sidekiq processes, you can create an additional process dedicated to indexing a set of queues (or queue group). This way, you can ensure that indexing queues always have a dedicated worker, while the rest of the queues have another dedicated worker to avoid contention.

For this purpose, use the routing rules option that allows Sidekiq to route jobs to a specific queue based on worker matching query.

To handle this, we generally recommend one of the following two options. You can either:

For the following steps, consider the entry of sidekiq['routing_rules']:

  • ["feature_category=global_search", "global_search"] as all indexing jobs are routed to the global_search queue.
  • ["*", "default"] as all other non-indexing jobs are routed to the default queue.

At least one process in sidekiq['queue_groups'] has to include the mailers queue, otherwise mailers jobs are not processed at all.

Note

Routing rules (sidekiq['routing_rules']) must be the same across all GitLab nodes (especially GitLab Rails and Sidekiq nodes).

Warning

When starting multiple processes, the number of processes cannot exceed the number of CPU cores you want to dedicate to Sidekiq. Each Sidekiq process can use only one CPU core, subject to the available workload and concurrency settings. For more details, see how to run multiple Sidekiq processes.

Single node, two processes

To create both an indexing and a non-indexing Sidekiq process in one node:

  1. On your Sidekiq node, change the /etc/gitlab/gitlab.rb file to:

    sidekiq['enable'] = true
    
    sidekiq['routing_rules'] = [
       ["feature_category=global_search", "global_search"],
       ["*", "default"],
    ]
    
    sidekiq['queue_groups'] = [
       "global_search", # process that listens to global_search queue
       "default,mailers" # process that listens to default and mailers queue
    ]
    
    sidekiq['concurrency'] = 20
    

    If you are using GitLab 16.11 and earlier, explicitly disable any queue selectors :

    sidekiq['queue_selector'] = false
    
  2. Save the file and reconfigure GitLab for the changes to take effect.

  3. On all other Rails and Sidekiq nodes, ensure that sidekiq['routing_rules'] is the same as the previous configuration.

  4. Run the Rake task to migrate existing jobs.

Note

It is important to run the Rake task immediately after reconfiguring GitLab. After reconfiguring GitLab, existing jobs are not processed until the Rake task starts to migrate the jobs.

Two nodes, one process for each

To handle these queue groups on two nodes:

  1. To set up the indexing Sidekiq process, on your indexing Sidekiq node, change the /etc/gitlab/gitlab.rb file to:

    sidekiq['enable'] = true
    
    sidekiq['routing_rules'] = [
       ["feature_category=global_search", "global_search"],
       ["*", "default"],
    ]
    
    sidekiq['queue_groups'] = [
      "global_search", # process that listens to global_search queue
    ]
    
    sidekiq['concurrency'] = 20
    

    If you are using GitLab 16.11 and earlier, explicitly disable any queue selectors :

    sidekiq['queue_selector'] = false
    
  2. Save the file and reconfigure GitLab for the changes to take effect.

  3. To set up the non-indexing Sidekiq process, on your non-indexing Sidekiq node, change the /etc/gitlab/gitlab.rb file to:

    sidekiq['enable'] = true
    
    sidekiq['routing_rules'] = [
       ["feature_category=global_search", "global_search"],
       ["*", "default"],
    ]
    
    sidekiq['queue_groups'] = [
       "default,mailers" # process that listens to default and mailers queue
    ]
    
    sidekiq['concurrency'] = 20
    

    If you are using GitLab 16.11 and earlier, explicitly disable any queue selectors :

    sidekiq['queue_selector'] = false
    
  4. On all other Rails and Sidekiq nodes, ensure that sidekiq['routing_rules'] is the same as the previous configuration.

  5. Save the file and reconfigure GitLab for the changes to take effect.

  6. Run the Rake task to migrate existing jobs.

    sudo gitlab-rake gitlab:sidekiq:migrate_jobs:retry gitlab:sidekiq:migrate_jobs:schedule gitlab:sidekiq:migrate_jobs:queued
    
Note

It is important to run the Rake task immediately after reconfiguring GitLab. After reconfiguring GitLab, existing jobs are not processed until the Rake task starts to migrate the jobs.

Sometimes there may be issues with your Elasticsearch index data and as such GitLab allows you to revert to “basic search” when there are no search results and assuming that basic search is supported in that scope. This “basic search” behaves as though you don’t have advanced search enabled at all for your instance and search using other data sources (such as PostgreSQL data and Git data).

Disaster recovery

Elasticsearch is a secondary data store for GitLab. All of the data stored in Elasticsearch can be derived again from other data sources, specifically PostgreSQL and Gitaly. If the Elasticsearch data store gets corrupted, you can reindex everything from scratch.

If your Elasticsearch index is too large, it might cause too much downtime to reindex everything from scratch. You cannot automatically find discrepancies and resync an Elasticsearch index, but you can inspect the logs for any missing updates. To recover data more quickly, you can replay:

  1. All synced non-repository updates by searching in elasticsearch.log for track_items . You must send these items again through ::Elastic::ProcessBookkeepingService.track!.
  2. All repository updates by searching in elasticsearch.log for indexing_commit_range . You must set IndexStatus#last_commit/last_wiki_commit to the oldest from_sha in the logs and then trigger another index of the project with Search::Elastic::CommitIndexerWorker and ElasticWikiIndexerWorker .
  3. All project deletes by searching in sidekiq.log for ElasticDeleteProjectWorker . You must trigger another ElasticDeleteProjectWorker.

You can also take regular Elasticsearch snapshots to reduce the time it takes to recover from data loss without reindexing everything from scratch.