Example - Index and query JSON documents
Learn how to use the Redis query engine with JSON
This example shows how to create a search index for JSON data and run queries against the index.
Make sure that you have Redis Stack and go-redis
installed.
Start by importing dependencies:
Connect to the database:
Create some test data to add to the database:
Use the code below to create a search index. The FTCreateOptions
parameter enables
indexing only for JSON objects where the key has a user:
prefix.
The
schema
for the index has three fields for the user's name, age, and city.
The FieldName
field of the FieldSchema
struct specifies a
JSON path
that identifies which data field to index. Use the As
struct field
to provide an alias for the JSON path expression. You can use
the alias in queries as a short and intuitive way to refer to the
expression, instead of typing it in full:
Add the three sets of user data to the database as
JSON objects.
If you use keys with the user:
prefix then Redis will index the
objects automatically as you add them:
You can now use the index to search the JSON objects. The
query
below searches for objects that have the text "Paul" in any field
and have an age
value in the range 30 to 40:
Specify query options to return only the city
field:
Use an aggregation query to count all users in each city.
See the Redis query engine docs for a full description of all query features with examples.