Search Users With OpenSearch or Elasticsearch
On this page
This guide shows how to search for Users with the Elasticsearch search engine. The Elasticsearch search engine works the same way with OpenSearch and Elasticsearch, so every example on this page works with both. Entity searches use the same parameters. For the Entity fields, see Indexed Entity Fields.
The examples use curl. To run the same searches from your application, use a client library.
Prerequisites#
- FusionAuth configured with the Elasticsearch search engine. To check the engine, navigate to System -> About in the Admin UI. The Search row shows
OpenSearchorElasticsearchwith the Elasticsearch search engine. To set up the engine, see Install a Search Engine. - An API key with access to the
/api/user/searchendpoint.
With the database search engine, the User Search API accepts only simple terms. For the differences between the engines, see Search Engines.
Search Parameters#
A search request uses one of the following parameters. The parameters are mutually exclusive.
| Parameter | Uses the search engine | Use for |
|---|---|---|
ids |
No | Retrieving Users whose Ids you know, for example from a webhook or from another data store. |
queryString |
Yes | Matching strings in one field or across all fields. |
query |
Yes | Full Elasticsearch queries across fields, including nested values, ranges, and compound clauses. |
nextResults |
Yes | Paging past the first 10,000 results of a queryString or query search. Available in FusionAuth 1.48.0 and later. |
You can send any search as a GET or a POST request. Both methods return the same results. A POST request can hold a larger query, so the examples on this page use POST.
Ids Searches#
An ids search retrieves Users from the database by Id. An ids search never queries the search engine, so an ids search works even when the search engine is down.
QueryString Searches#
A queryString search matches without regard to case. URL-encode whitespace in a GET request, for example as %20. You can use Elasticsearch wildcards, such as * for a prefix or suffix match. To search one field, prefix the value with the field name, such as email:.
FusionAuth changes the queryString before sending the query to the search engine:
- When the value contains a
:, FusionAuth sends the value as is. - When the value contains an
@and no spaces, FusionAuth treats the value as an email address and adds theemail:prefix. - When the value contains no spaces, FusionAuth adds a
*wildcard to the start and the end.
FusionAuth adds wildcards to unscoped queryStrings in order to match the broadest set of results. Depending on the specifics of the system, a leading wildcard on a search term can significantly reduce search performance. In order to improve search performance, limit the search to a single field by specifying it in the queryString followed by a : to prevent the pre-processing by FusionAuth.
The Admin UI changes the search value further, so a search in the Admin UI can return different results than the same value sent to the API.
Use AND and OR to combine clauses.
Query Searches#
The query parameter takes an Elasticsearch query as an escaped JSON string. FusionAuth passes the query to the search engine, so you can use the full Elasticsearch query language.
Next Results Searches#
Available since1.48.0
Every queryString and query search returns a nextResults token. Send the token in the next request to get the page that follows the previous results. For an example, see Extended Pagination.
Field Mappings#
queryString and query searches can match specific fields. For the fields you can search, see Indexed User Fields.
The search engine indexes the following relationships of each User as nested fields. To search nested fields, use a query search with the nested query type:
memberships, the User's Group membershipsregistrations, the User's Application registrations
Results of a User Search#
Every search returns the same format: a total count of the matching Users, and a users array of User objects.
{
"expandable": [],
"nextResults": "eyJscyI6WyIxLjAwMTQ2MTkiLG51bGwsInRlc3R1c2VyOTkwOUBsb2NhbC5jb20iLCJjNmI4ZjQyNC0wOTRjLTQ1MWYtYWMxNS05Y2ZkODI3NTZlNGEiXSwicXMiOiIqIiwic2YiOltdfQ",
"total": 1,
"users": [
{
"active": true,
"birthDate": "1976-05-30",
"breachedPasswordLastCheckedInstant": 1471786483322,
"breachedPasswordStatus": "None",
"data": {
"displayName": "Johnny Boy",
"favoriteColors": [
"Red",
"Blue"
]
},
"email": "example@fusionauth.io",
"expiry": 1571786483322,
"firstName": "John",
"fullName": "John Doe",
"id": "00000000-0000-0001-0000-000000000000",
"identities": [
{
"insertInstant": 1742936980069,
"lastLoginInstant": 1742936980069,
"lastUpdateInstant": 1742936980069,
"primary": true,
"type": "email",
"value": "example@fusionauth.io",
"verified": false,
"verifiedReason": "Disabled"
},
{
"insertInstant": 1742936980069,
"lastLoginInstant": 1742936980069,
"lastUpdateInstant": 1742936980069,
"primary": true,
"type": "phoneNumber",
"value": "+13035551212",
"verified": false,
"verifiedReason": "Disabled"
},
{
"displayValue": "johnny123",
"insertInstant": 1742936980069,
"lastLoginInstant": 1742936980069,
"lastUpdateInstant": 1742936980069,
"moderationStatus": "ACTIVE",
"primary": true,
"type": "username",
"value": "johnny123",
"verified": false,
"verifiedReason": "Unverifiable"
}
],
"imageUrl": "http://65.media.tumblr.com/tumblr_l7dbl0MHbU1qz50x3o1_500.png",
"insertInstant": 1742936980069,
"lastLoginInstant": 1742936980069,
"lastName": "Doe",
"middleName": "William",
"mobilePhone": "303-555-1234",
"passwordChangeRequired": false,
"passwordLastUpdateInstant": 1742936980069,
"phoneNumber": "+13035551212",
"preferredLanguages": [
"en",
"fr"
],
"registrations": [
{
"applicationId": "10000000-0000-0002-0000-000000000001",
"data": {
"displayName": "Johnny",
"favoriteSports": [
"Football",
"Basketball"
]
},
"id": "00000000-0000-0002-0000-000000000000",
"insertInstant": 1742936980069,
"lastLoginInstant": 1742936980069,
"preferredLanguages": [
"en",
"fr"
],
"roles": [
"user",
"community_helper"
],
"username": "johnny123",
"usernameStatus": "ACTIVE",
"verified": true,
"verifiedInstant": 1742936980069
}
],
"timezone": "America/Denver",
"tenantId": "f24aca2b-ce4a-4dad-951a-c9d690e71415",
"twoFactor": {
"methods": [
{
"authenticator": {
"algorithm": "HmacSHA1",
"codeLength": 6,
"timeStep": 30
},
"id": "35VW",
"method": "authenticator"
},
{
"id": "V7SH",
"method": "sms",
"mobilePhone": "555-555-5555"
},
{
"email": "example@fusionauth.io",
"id": "7K2G",
"method": "email"
}
]
},
"usernameStatus": "ACTIVE",
"username": "johnny123",
"verified": true,
"verifiedInstant": 1742936980069
}
]
}User Search Examples#
The following examples come from the FusionAuth user search example repository. To run the examples against your own instance, follow the instructions in the README.
Each example runs the search with the following shell script. Set your API key and FusionAuth URL in the script before you run the examples. The script sends a POST request, so the request body can be large. Each example passes a different file name to the script.
#!/bin/sh
FILE=$1
API_KEY=90d8fb62-6f13-47d4-8ef6-1c3e687883c6
BASE_URL='http://localhost:9011'
#BASE_URL='https://sandbox.fusionauth.io'
curl -XPOST \
-H 'Content-type: application/json' \
-H "Authorization: $API_KEY" \
$BASE_URL'/api/user/search' \
-d @$FILESearch by User Ids#
The following request retrieves Users by Id:
{
"search": {
"ids": [
"00000000-0000-0000-0000-000000000001",
"00000000-0000-0000-0000-000000000002"
]
}
}
Save the request as ids-request.json, and pass the file name to search.sh:
$ ./search.sh ids-request.json
Search With queryString#
All Fields#
The following request searches every field for dinesh. FusionAuth adds a wildcard to the start and the end of the value.
{
"search": {
"numberOfResults": 50,
"queryString": "dinesh",
"sortFields": [
{
"missing": "_first",
"name": "email",
"order": "asc"
}
],
"startRow": 0
}
}Save the request as all-fields-data-request.json, and run the script:
$ ./search.sh all-fields-data-request.json
Email#
The following request searches only the email field for dinesh, because the value starts with email:.
{
"search": {
"numberOfResults": 50,
"queryString": "email:dinesh*",
"sortFields": [
{
"missing": "_first",
"name": "email",
"order": "asc"
}
],
"startRow": 0
}
}FusionAuth doesn't add wildcards to a value with a field prefix. So email:dinesh returns no Users, because no User has the email address dinesh. The value email:dinesh@fusionauth.io returns the User.
Multiple Fields#
The following request matches Users whose email field matches dinesh, or whose verified field is false. The OR clause returns a User when either clause matches. Use AND to return only Users that match both clauses.
{
"search": {
"numberOfResults": 50,
"queryString": "email:dinesh* OR verified:true",
"sortFields": [
{
"missing": "_first",
"name": "email",
"order": "asc"
}
],
"startRow": 0
}
}For the query string syntax, see the Elasticsearch query string documentation.
Phone Number#
Available since1.59.0
The following request searches only the phoneNumber field, because the value starts with phoneNumber:. The query matches phone numbers with any country code and the 303 area code.
{
"search": {
"numberOfResults": 25,
"queryString": "phoneNumber:303*",
"sortFields": [
{
"missing": "_first",
"name": "phoneNumber",
"order": "asc"
}
],
"startRow": 0
}
}Exact Username or Full Name#
Available since1.49.1
The following request searches the fullName.exact field, so the request returns only users whose full name is Bob Smith, ignoring case. A search on the fullName field matches words within a name instead, so fullName:Edwards returns every user with Edwards anywhere in the full name. The double quotes keep the space as part of the value. For more information, see Exact Match Fields.
{
"search": {
"numberOfResults": 25,
"queryString": "fullName.exact:\"Bob Smith\"",
"startRow": 0
}
}Search With query#
The query parameter takes an escaped Elasticsearch query, which FusionAuth passes to the search engine. A query search can use every feature of the Elasticsearch query language.
Search One Field#
First, build the Elasticsearch query. The following query matches every User with a user.data.Company value of PiedPiper.
The user.data field holds any JSON, such as custom profile fields. Many FusionAuth objects have a data field, but the search engine indexes only user.data, registration.data, and entity.data.
The key is case-sensitive, so a search on user.data.company returns no Users. The value is case-insensitive, so PiedPiper, piedpiper, and PIEDPIPER return the same Users.
{
"match": {
"data.Company": {
"query": "PiedPiper"
}
}
}Next, escape the query. The FusionAuth request body is JSON, and the query is JSON inside a string, so you must escape the quotes and other JSON characters in the query. A queryString search doesn't need this step.
To escape the query with jq, save the query as queryfile and run the following command. The output contains \n newline characters, which the search engine ignores.
$ cat queryfile | jq -R -s '.'
The command prints the escaped query:
"{\n \"match\": {\n \"data.Company\": {\n \"query\": \"PiedPiper\"\n }\n }\n}\n"Next, set the escaped query as the query parameter of a request:
{
"search": {
"numberOfResults": 50,
"query":"{\n \"match\": {\n \"data.Company\": {\n \"query\": \"PiedPiper\"\n }\n }\n}\n",
"sortFields": [
{
"missing": "_first",
"name": "email",
"order": "asc"
}
],
"startRow": 0
}
}Save the request as user-data-simple-request.json, and run the script:
$ ./search.sh user-data-simple-request.json
Search Several Fields#
A query search can combine clauses, nested queries, and numeric ranges. The following query combines several clauses:
{
"bool": {
"must": [
{
"range": {
"data.Salary": {
"lt": 100000
}
}
},
{
"match": {
"data.Company": {
"query": "PiedPiper"
}
}
},
{
"match": {
"verified": {
"query": true
}
}
},
{
"nested": {
"path": "registrations",
"query": {
"bool": {
"must": [
{
"match": {
"registrations.data.paid": false
}
}
]
}
}
}
}
]
}
}The query matches Users who meet all of the following criteria:
- A salary of less than 100000.
- Pied Piper employment.
- A verified email address.
- Registered for a particular application in your system. The
registrationsobject is nested. - For that particular application, having a paid attribute of
false.
Escape the query with jq:
$ cat queryfile | jq -R -s '.'
The command prints the escaped query:
"{\n \"bool\": {\n \"must\": [\n {\n \"range\": {\n \"data.Salary\": {\n \"lt\": 100000\n }\n }\n },\n {\n \"match\": {\n \"data.Company\": {\n \"query\": \"PiedPiper\"\n }\n }\n },\n {\n \"match\": {\n \"verified\": {\n \"query\": true\n }\n }\n },\n { \n \"nested\" : {\n \"path\" : \"registrations\",\n \"query\" : {\n \"bool\" : {\n \"must\" : [ {\n \"match\" : {\n \"registrations.applicationId\" : \"e9fdb985-9173-4e01-9d73-ac2d60d1dc8e\"\n },\n \"match\" : {\n \"registrations.data.paid\" : false\n }\n } ]\n }\n }\n }\n }\n ]\n }\n}\n"Set the escaped query as the query parameter of a request:
{
"search": {
"numberOfResults": 50,
"query": "{\n \"bool\": {\n \"must\": [\n {\n \"range\": {\n \"data.Salary\": {\n \"lt\": 100000\n }\n }\n },\n {\n \"match\": {\n \"data.Company\": {\n \"query\": \"PiedPiper\"\n }\n }\n },\n {\n \"match\": {\n \"verified\": {\n \"query\": true\n }\n }\n },\n { \n \"nested\" : {\n \"path\" : \"registrations\",\n \"query\" : {\n \"bool\" : {\n \"must\" : [ {\n \"match\" : {\n \"registrations.applicationId\" : \"e9fdb985-9173-4e01-9d73-ac2d60d1dc8e\"\n },\n \"match\" : {\n \"registrations.data.paid\" : false\n }\n } ]\n }\n }\n }\n }\n ]\n }\n}\n",
"sortFields": [
{
"missing": "_first",
"name": "email",
"order": "asc"
}
],
"startRow": 0
}
}Save the request as user-data-complex-request.json, and run the script:
$ ./search.sh user-data-complex-request.json
The response contains every User that matches all the criteria.
Search in the Admin UI#
The Admin UI can build queryString and query values for the User Search API and the Bulk Delete Users API. Navigate to Users , and click Advanced below the Search field. The Advanced link appears only with the Elasticsearch search engine.
Pick values for common fields, or type a query string or JSON query in the search field. Turn on Show Elasticsearch query to see the query string or JSON query that the Admin UI sends. Copy the value into the queryString or query parameter of an API request.
The following screenshot shows a query string for Users in the Moderators Group and in the Default Tenant:

A search on an Application, or on a field of an Application, needs a JSON query, because the index maps registrations as nested fields. The following screenshot shows a JSON query for Users registered to the Pied Piper Application with the CEO role and an email address that matches *@fusionauth.io:

When a search matches more than 10,000 Users, click Last to go to the page with the 10,000th result. Then click Next to page forward one page at a time until the last result. In FusionAuth versions before 1.48.0, paging past 10,000 results returns an error.
Pagination#
You often need to paginate the results when running a query that matches many users or entities.
You can use the numberOfResults and startRow parameters to do so.
{/* this is pseudo code and won't work out of the box */}
{/* adapt for whichever client and programming language you are using */}
startRow = 0
numberOfResults = 25
fullresults = [] // new array
results = client.search(query, startRow, numberOfResults)
count = results.length
fullresults.append(results)
while (count > 0) {
startRow = startRow + count
results = client.search(query, startRow, numberOfResults)
fullresults.append(results)
count = results.length
}
{/* process fullresults here */}
You may also set numberOfResults to a higher number (500 or 5000, for example) to retrieve more results.
However, processing results 25 or 50 at a time has less impact on the FusionAuth system.
In FusionAuth versions before 1.48.0, a search returns at most 10,000 results, however you paginate. For workarounds, see Limitations.
Extended Pagination#
Available since1.48.0
Every queryString and query search returns a nextResults token. Send the token in the next request, and FusionAuth returns the page that follows the previous results, with a new token. Repeat until a request returns no Users. With the token, you can page past the 10,000 result limit of startRow.
FusionAuth builds the query from the token, so a request with nextResults accepts only numberOfResults as another parameter. Internally, FusionAuth turns the token into an Elasticsearch search_after query. For more information, see the Elasticsearch pagination documentation.
The following search finds all Users. The accurateTotal parameter returns the true count of matching Users instead of a count capped at 10,000:
{
"search": {
"accurateTotal": true,
"numberOfResults": 25,
"queryString": "*",
"sortFields": [
{
"missing": "_first",
"name": "email",
"order": "asc"
}
],
"startRow": 0
}
}The response includes a nextResults token:
{
"nextResults": "eyJscyI6WyIxLjAwMTQ2MTkiLG51bGwsInRlc3R1c2VyOTkwOUBsb2NhbC5jb20iLCJjNmI4ZjQyNC0wOTRjLTQ1MWYtYWMxNS05Y2ZkODI3NTZlNGEiXSwicXMiOiIqIiwic2YiOltdfQ",
"total": 12009,
"users": [
...
]
}
A request with a startRow greater than 10,000 returns an error. To reach later results, send the same query with a startRow of 9975 and a numberOfResults of 25. Then send the nextResults token from that response:
{
"search": {
"numberOfResults": 25,
"nextResults": "eyJscyI6WyIxLjAwMTQ2MTkiLG51bGwsInRlc3R1c2VyOTkwOUBsb2NhbC5jb20iLCJjNmI4ZjQyNC0wOTRjLTQ1MWYtYWMxNS05Y2ZkODI3NTZlNGEiXSwicXMiOiIqIiwic2YiOltdfQ"
}
}The response contains Users 10,001 through 10,025, and a new token. Send each new token to get the next 25 Users.
The following script pages through every User with nextResults tokens:
#!/bin/bash
API_KEY=this_really_should_be_a_long_random_alphanumeric_value_but_this_still_works
BASE_URL=http://localhost:9011
tmpdir=tmp.$$
mkdir $tmpdir
results=$(curl -s -XPOST \
-H 'Content-type: application/json' \
-H "Authorization: $API_KEY" \
$BASE_URL'/api/user/search' \
-d '{
"search": {
"accurateTotal": true,
"numberOfResults": 1000,
"queryString": "*",
"sortFields": [
{
"missing": "_first",
"name": "email",
"order": "asc"
}
],
"startRow": 0
}
}')
# output the first set of users
echo ${results} > $tmpdir/file.first
users=$(echo ${results} | jq -r '.users')
usersCount=$(echo ${users} | jq -r length)
totalUsers=$(echo $results | jq -r .total)
totalUsers=$(($totalUsers - $usersCount))
nextResults=$(echo $results | jq -r .nextResults)
# get the next set of users
while [ $totalUsers -gt 0 ]
do
printf "."
results=$(curl -s -XPOST \
-H 'Content-type: application/json' \
-H "Authorization: $API_KEY" \
$BASE_URL'/api/user/search' \
-d '{
"search": {
"numberOfResults": 1000,
"nextResults": "'${nextResults}'"
}
}')
# output the next set of users
echo ${results} > $tmpdir/file.${nextResults}
users=$(echo ${results} | jq -r '.users')
usersCount=$(echo ${users} | jq -r length)
# update remaining user count to be retrieved
totalUsers=$(($totalUsers - $usersCount))
nextResults=$(echo $results | jq -r .nextResults)
done
jq 'reduce inputs as $i (.; .users += $i.users)| del(.total)|del(.nextResults)' $tmpdir/file*> users.json
rm -rf $tmpdirTroubleshooting Elasticsearch Queries#
When you are troubleshooting Elasticsearch queries, running them against the Elasticsearch server is helpful.
If you are running in FusionAuth Cloud, you cannot access Elasticsearch in the manner described here.
When running FusionAuth locally in Docker, you can expose the Elasticsearch port by adding the following lines to your docker-compose.yml file and restarting.
# ... other stuff
search:
# ... other stuff
ports:
- 9200:9200
Once you've opened up the port, you can query Elasticsearch directly. Here's an example of a single field query.
$ curl -X GET "localhost:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"match": {
"data.Company": {
"query": "PiedPiper"
}
}
}
}'
When you run this curl command, you'll get back results similar to below.
{
"took" : 6,
"timed_out" : false,
"_shards" : {
"total" : 10,
"successful" : 10,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score" : 2.0,
"hits" : [
{
"_index" : "fusionauth_user",
"_type" : "_doc",
"_id" : "00000000-0000-0000-0000-000000000003",
"_score" : 2.0
},
{
"_index" : "fusionauth_user",
"_type" : "_doc",
"_id" : "00000000-0000-0000-0000-000000000006",
"_score" : 2.0
},
{
"_index" : "fusionauth_user",
"_type" : "_doc",
"_id" : "00000000-0000-0000-0000-000000000005",
"_score" : 2.0
}
]
}
}
When debugging, examine the hits.hits array. The _id value corresponds to the user Id that matched your query. If the content or number of users returned are different than expected, modify the query.
When a search misses Users that exist, the index might be out of sync with the database. For more information, see Reindex.
Limitations#
A search returns whole User objects. You can't limit the results to certain fields. To keep only some fields, such as firstName and birthDate, filter the results in your code, or with a tool such as jq.
In FusionAuth versions before 1.48.0, a search with the Elasticsearch search engine returns at most 10,000 Users. In 1.48.0 and later, you can page through every result with nextResults tokens.
The Elasticsearch search index is eventually consistent. After an update through the API, a change appears in search results once FusionAuth sends the change to the search engine and the search engine refreshes the index. The search engine refreshes the index every second by default, so changes take at least one second to appear. For more information, see the Elasticsearch refresh_interval setting.
Maximum Users Returned Workarounds#
1.48.0With the Elasticsearch search engine, page past 10,000 results with the nextResults token. For more information, see Extended Pagination.
In earlier versions, split a search into queries that each return fewer than 10,000 Users. To check whether a query matches more than 10,000 Users, set the accurateTotal parameter. For more information, see the User Search API.
For example, to download every User, query for email addresses that start with a, then b, and so on. For a script that uses this approach, see the full user search example.
When you self-host FusionAuth, you can also query the search engine directly. Each document Id in the result is a FusionAuth User Id. To retrieve the Users, send the Ids to the User Search API with the ids parameter.
Changing Data Field Types#
Each field in a data object must hold one data type across all Users. The search engine skips Users with a mismatched type. For more information, see Data Field Types.
Example Repository#
To run every example on this page against your own instance, clone the FusionAuth user search example repository and follow the instructions in the README. For every User Search API parameter, see the User Search API.
Related
API documentation for the Search for Users API.
Learn how to install OpenSearch and connect FusionAuth to OpenSearch for advanced user and entity search.
Learn about the database and Elasticsearch search engines, which FusionAuth features use each engine, and how to choose one.
Learn how to switch FusionAuth between the database search engine and the Elasticsearch search engine.