How to create a search context with the GraphQL API

This document will take you through how to create a search context for your user with Sourcegraph's GraphQL API.

Prerequisites

Steps to create

Step 1: Add to global configuration (must be site-admin):

{
    "experimentalFeatures": {
      "showSearchContext": true,
      "showSearchContextManagement": true
  }
}

Step 2: Make sure you have added code hosts: Add repositories (from code hosts) to Sourcegraph

Step 3: Follow the steps to Generate an access token for GraphQL if you already haven't

Step 4: Navigate to the API console on your instance, replacing sourcegraph.example with the correct string for your instance URL.

Step 5: Query your user namespace id and save the value

  • The name: will be your Sourcegraph instance login name Example:
query {
  namespaceByName(name: "my_login_name") {
    id
  }
}

Step 6: Query your desired repo id and save the value.

  • It should be whatever the URL is for that repo. Example:
query {
  repository(name: "github.com/org_name/repo_name") {
    id
  }
}

Step 7: Take the values from steps 5 and 6 and put them into the example variables from our docs here:

Run this with no changes:

mutation CreateSearchContext(
  $searchContext: SearchContextInput!
  $repositories: [SearchContextRepositoryRevisionsInput!]!
) {
  createSearchContext(searchContext: $searchContext, repositories: $repositories) {
    id
    spec
  }
}

Then in the Query Variables section on the bottom of the GraphQL API page, use this variables example, changing at least the name and description:

{
  "searchContext": {
    "name": "MySearchContext",
    "description": "A description of my search context",
    "namespace": "user-id-from-step-5",
    "public": true
  },
  "repositories": [
    {
      "repositoryID": "repo-id-from-step-6",
      "revisions": ["main", "branch-1"]
  	}
  ]
}

Step 8: Run the query, that should create a search context and the output will look something like:

{
  "data": {
    "createSearchContext": {
      "id": "V2VhcmNoQ29udGV4dDoiQGdpc2VsbGUvTXlTZWFyY2hDb250ZXh0MiI=",
      "spec": "@my_login_name/MySearchContext"
    }
  }
}

Step 9: Go to the main search page and you should see the new Search context as part of the search bar!

Further resources