Code Search
Code Search finds code across every repository you can access in Sourcegraph, on every connected code host. It searches file contents, file paths, and commit history. You start with the words you expect to see, then refine the query until the results answer your question: narrow where to look, exclude noise, or get a list of repositories instead of matching lines.
Code Search is available on Enterprise Starter and Enterprise plans, in the web app and in the VS Code and JetBrains editor extensions.
You can use it for:
- Finding references to a function, API, or configuration key before you change or remove it.
- Answering "which repositories use X?", such as a library, a base image, or a deprecated pattern.
- Tracking down leaked secrets, hard-coded hosts, or other strings that should not be in code.
- Finding when code appeared or disappeared, and who changed it, by searching diffs and commit messages.
- Finding who owns code, or which code has no owner, with code ownership.
- Getting notified when a pattern appears in new commits, instead of finding it later.
Some terms used in this documentation:
- A query is what you type in the search box. It can include a search pattern, the text to match, and filters such as
repo:,file:, orlang:that limit where to look. - A search context is a named set of repositories that every search runs inside,
globalby default. See Search contexts.
Search step by step
Python 3.12 deprecated datetime.utcnow() and datetime.utcfromtimestamp(). Their replacements return timezone-aware values, so your team must find and review every call before changing it. The steps below follow that task from a first query to the answer.
The examples search public Apache projects, and the run button next to each query runs it on sourcegraph.com. On your own instance, use your organization's repositories. Example queries shows queries for more tasks, such as finding leaked keys or checking which release contains a change.
Start with the words you know
Type what you expect to see in the code:
Code Search returns files, paths, and repository names that contain the term, in any repository in your search context. You can also describe what you want in plain language with query assist.
Narrow down where to look
The first query searches every repository and also matches documentation and other languages. Filters keep only Python files in the repositories you care about, here three Apache projects:
repo: matches repository names with a regular expression, here three exact names, and lang: restricts results to files in one language. Query syntax lists every filter.
Match the calls
utcnow also matches comments and longer names such as get_utcnow, and it misses utcfromtimestamp. A regular expression between slashes matches the common spellings of both calls:
repo:^github\.com/apache/(airflow|superset|beam)$ lang:python /datetime\.utc(now|fromtimestamp)\(/This also matches datetime.datetime.utcnow(). It is still a text match: comments and strings can match, and calls through an alias, such as dt.utcnow(), are missed. Review the results before you act on them.
Get the list of repositories
You need the repositories to follow up with, not every line:
repo:^github\.com/apache/(airflow|superset|beam)$ lang:python /datetime\.utc(now|fromtimestamp)\(/ select:reposelect:repo returns each matching repository once instead of every matching line.
Look at the history
type:diff searches commit changes instead of current code. Before you plan your own change, see how another project made it. This query finds Airflow commits that removed the calls between July 2023 and July 2024, with the author, date, and changed lines of each:
repo:^github\.com/apache/airflow$ lang:python type:diff after:2023-07-01 before:2024-07-01 select:commit.diff.removed /datetime\.utc(now|fromtimestamp)\(/select:commit.diff.removed keeps matches on removed lines; select:commit.diff.added finds new calls instead. History searches are slower than content searches, so keep them scoped with repo: and a date filter.
Build on a query
Once a query gives the right answer, you can reuse it:
- Track progress. A code insight charts the matches of the content query over time, so you can watch the remaining calls go down.
- Get notified. A code monitor checks new commits with a
type:diffquery for the same pattern and alerts you when someone adds a new call. - Save the scope. If you search the same repositories often, a search context replaces the repeated
repo:filters. - Save the query. A saved search keeps the query so you can run it again.
- Export the matches. A search job runs the content query, without
select:repo, in the background and collects the matches for download. - Fix it everywhere. Agentic Batch Changes can use your findings to open changesets that replace the calls across repositories.
Search contexts
A search context is a named set of repositories, optionally at specific revisions. Use one to search the code that matters to you, such as your team's services or a release, without repeating repo: filters in every query.
Search a context with context:<name>. A query without one uses your default context, or global, which includes every repository you can access. A context never grants access: searches only return results from repositories you can see. Combine contexts with OR:
(context:release1 OR context:release2) someTerribleBugContexts can belong to a user (context:@alice/backend), an organization (context:@acme/platform), or the whole instance (context:release-2026), and can be private or public. The owner can't be changed later. Administrators, and users with the permission to write instance-level search contexts, can create instance-level contexts. Names have at most 32 characters: letters, digits, ., _, /, and -. You can star contexts and choose your own default. Administrators can set a default for the instance or for an organization; your own default always wins.
Query-based search contexts
A context's repositories come from a fixed list of repositories and revisions, or from a search query. A query defines a set that changes over time, such as every repository in an organization with a topic:
repo:^github\.com/acme/ repo:has.topic(backend)The query can use repo: with metadata predicates such as repo:has.topic(), and file:, lang:, case:, fork:, archived:, and visibility:. A repo: filter can name revisions, such as repo:^github\.com/acme/api$@v2.0.0. The query can't contain a search pattern, content predicates such as repo:has.file(), or revision globs.
Administrators can index the revisions that query-based contexts match, so that searching them is fast.
Saved searches
A saved search keeps a query so that you and your team can run it again. A saved search belongs to you or to an organization you're a member of. Only its owner can see it unless it is public. Administrators, and users with the permission to create public library items, can make a saved search public to everyone on the instance. To be alerted when new code matches a query, use a code monitor instead.
Search jobs
A search job runs a query in the background and collects every match, without the result limit and timeout of interactive searches. Use one when you need a complete list across many repositories, for example for an audit or a migration plan. Search jobs are available on Enterprise plans.
An interactive search with count:all also asks for every result, but it still stops at the timeout. If the search finishes within the timeout, you can export up to 100,000 results as CSV. If it times out or you need more, use a search job.
To create a job, run the query and choose Create search job in the Actions menu of the search results. Your jobs are listed on the Search Jobs page (/search-jobs on your instance), where you can download each job's results and log. Results are JSON Lines, in the same format as match events from the Stream API. Jobs stay until you delete them, and administrators can see every user's jobs.
To search every branch of every repository, add a revision glob:
repo:.* rev:*refs/heads/* fooA job runs with your repository permissions and searches every revision in its scope, including branches that aren't indexed. As in interactive search, forks and archived repositories are skipped unless you add fork:yes or archived:yes. Two mistakes give incomplete results without an error:
- Adding
count:. In a job, it caps the matches of each repository revision separately, not the total, and the job still completes. - Naming a revision that doesn't exist, such as a misspelled branch. It is skipped.
Search jobs support file content, path, commit, and diff searches, not type:symbol or type:repo. They don't support select:, index:, file predicates such as file:has.content() or file:has.owner(), structural search, or a regular expression that is only .*. AND and OR work between search patterns, such as TODO OR FIXME, but not between parts that need different filters, such as (lang:go TODO) OR (lang:markdown FIXME). Split such a query into several jobs.
A job fails if the search of any repository or revision fails, and its log shows which one and why. Split a failing or slow query into smaller jobs, for example by repository.
To create and download jobs from scripts, use the search jobs service of the Sourcegraph API. For automation, create jobs as a service account with access to the repositories you want to search. On a self-hosted instance, administrators can turn search jobs off and tune them.
Query assist
Query assist turns a plain-language description into a query that you can run or edit. Type # in the search box, then describe what you want. Filters typed before # stay in the query.
| Description | Suggested query |
|---|---|
| "TODO comments in python files" | lang:python TODO |
| "find function definitions for parseJSON" | type:symbol select:symbol.function parseJSON |
| "what did alice work on in the acme/backend repo?" | repo:acme/backend type:commit author:alice |
Query assist uses a large language model (see AI models), so actual suggestions can differ from these and can be wrong. Check a query before you rely on its results. Query assist requires a license with AI features, and administrators can turn it off.
When to use something else
Code Search works best when you can describe the text you're looking for. Other tools fit other questions:
- You have a question, not a pattern. Ask Deep Search, for example "How do our services authenticate to the billing API?" It runs searches for you and answers with sources.
- You're reading code and want a definition or its references. Use Code Navigation from the file view.
- You know the name of a file, symbol, or repository. Open it with the command palette, without a full search: press
Cmd+K(Ctrl+Kon Linux and Windows) on any page.