|
| 1 | +--- |
| 2 | +categories: |
| 3 | +- docs |
| 4 | +- develop |
| 5 | +- stack |
| 6 | +- oss |
| 7 | +- rs |
| 8 | +- rc |
| 9 | +- oss |
| 10 | +- kubernetes |
| 11 | +- clients |
| 12 | +description: Learn how to use the Redis query engine with JSON |
| 13 | +linkTitle: JSON query example |
| 14 | +title: Example - Index and query JSON documents |
| 15 | +weight: 2 |
| 16 | +--- |
| 17 | + |
| 18 | +This example shows how to create a |
| 19 | +[search index]({{< relref "/develop/interact/search-and-query/indexing" >}}) |
| 20 | +for [JSON]({{< relref "/develop/data-types/json" >}}) data and |
| 21 | +run queries against the index. |
| 22 | + |
| 23 | +Make sure that you have Redis Stack and `Jedis` installed. |
| 24 | + |
| 25 | +Start by importing dependencies: |
| 26 | + |
| 27 | +{{< clients-example java_home_json import >}} |
| 28 | +{{< /clients-example >}} |
| 29 | + |
| 30 | +Connect to the database: |
| 31 | + |
| 32 | +{{< clients-example java_home_json connect >}} |
| 33 | +{{< /clients-example >}} |
| 34 | + |
| 35 | +Create some test data to add to the database: |
| 36 | + |
| 37 | +{{< clients-example java_home_json create_data >}} |
| 38 | +{{< /clients-example >}} |
| 39 | + |
| 40 | +Create an index. In this example, only JSON documents with the key prefix `user:` are indexed. For more information, see [Query syntax]({{< relref "/develop/interact/search-and-query/query/" >}}). |
| 41 | + |
| 42 | +{{< clients-example java_home_json make_index >}} |
| 43 | +{{< /clients-example >}} |
| 44 | + |
| 45 | +Add the three sets of user data to the database as |
| 46 | +[JSON]({{< relref "/develop/data-types/json" >}}) objects. |
| 47 | +If you use keys with the `user:` prefix then Redis will index the |
| 48 | +objects automatically as you add them: |
| 49 | + |
| 50 | +{{< clients-example java_home_json add_data >}} |
| 51 | +{{< /clients-example >}} |
| 52 | + |
| 53 | +You can now use the index to search the JSON objects. The |
| 54 | +[query]({{< relref "/develop/interact/search-and-query/query" >}}) |
| 55 | +below searches for objects that have the text "Paul" in any field |
| 56 | +and have an `age` value in the range 30 to 40: |
| 57 | + |
| 58 | +{{< clients-example java_home_json query1 >}} |
| 59 | +{{< /clients-example >}} |
| 60 | + |
| 61 | +Specify query options to return only the `city` field: |
| 62 | + |
| 63 | +{{< clients-example java_home_json query2 >}} |
| 64 | +{{< /clients-example >}} |
| 65 | + |
| 66 | +Use an |
| 67 | +[aggregation query]({{< relref "/develop/interact/search-and-query/query/aggregation" >}}) |
| 68 | +to count all users in each city. |
| 69 | + |
| 70 | +{{< clients-example java_home_json query3 >}} |
| 71 | +{{< /clients-example >}} |
| 72 | + |
| 73 | +See the [Redis query engine]({{< relref "/develop/interact/search-and-query" >}}) docs |
| 74 | +for a full description of all query features with examples. |
0 commit comments