{
  "schema_version": 2,
  "id": "integrate/redisom-for-java",
  "title": "RedisOM for Java",
  "url": "https://redis.io/docs/latest/integrate/redisom-for-java/",
  "summary": "Learn how to build with Redis Stack and Spring",
  "aliases": [
    "/connect/clients/om-clients/stack-spring/",
    "/develop/connect/clients/om-clients/stack-spring/"
  ],
  "tags": [
    "docs",
    "integrate",
    "oss",
    "rs",
    "rc"
  ],
  "last_updated": "2026-09-17T14:54:53+01:00",
  "children": [],
  "page_type": "content",
  "content_hash": "2643ae0fc5bc7923fa0eb8dd0e24f6f86200e7de3e2217c5aeccd224906cdd73",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "Redis Stack provides a seamless and straightforward way to use different data models and functionality from Redis, including a document store, a time series data database, probabilistic data structures, and a full-text search engine.\n\nRedis Stack is supported by several client libraries, including Node.js, Java, and Python, so that developers can use their preferred language. We'll be using one of the Redis Stack supporting libraries; [Redis OM Spring](https://github.com/redis/redis-om-spring).\nRedis OM Spring provides a robust repository and custom object-mapping abstractions built on the powerful Spring Data Redis (SDR) framework."
    },
    {
      "id": "what-youll-need",
      "title": "What you’ll need:",
      "role": "content",
      "text": "* Redis Stack: See [Install Redis Open Source](https://redis.io/docs/latest/operate/oss_and_stack/install/install-stack)\n* [Redis Insight](https://redis.io/docs/latest/develop/tools/insight)\n* Your favorite browser\n* Java 11 or greater"
    },
    {
      "id": "spring-boot-scaffold-with-spring-initializer",
      "title": "Spring Boot scaffold with Spring Initializer",
      "role": "content",
      "text": "We’ll start by creating a skeleton app using the [Spring Initializer](https://start.spring.io), open your browser to https://start.spring.io and let's configure our skeleton application as follows:\n\n* We’ll use a Maven-based build (check Maven checkbox)\n* And version **`2.6.4`** of Spring Boot which is the current version supported by Redis OM Spring\n* Group: **`com.redis.om`**\n* Artifact: **`skeleton`**\n* Name: **`skeleton`**\n* Description: Skeleton App for Redis OM Spring\n* Package Name: **`com.redis.om.skeleton`**\n* Packaging: JAR\n* Java: **`11`**\n* Dependencies: **`web`**, **`devtools`** and **`lombok`**.\n\nThe `web` (Spring Web) gives us the ability to build RESTful applications using Spring MVC. With `devtools` we get fast application restarts and reloads. And `lombok` reduces boilerplate code like getters and setters.\n\n![Spring Initializer](./images/001_stack_spring.png \"Spring Initializer\")\n\nClick `Generate` and download the ZIP file, unzip it and load the Maven project into your IDE of choice."
    },
    {
      "id": "adding-redis-om-spring",
      "title": "Adding Redis OM Spring",
      "role": "content",
      "text": "Open the Maven `pom.xml` and between the `<dependencies>` and `<build>` sections we’ll add the snapshots repositories so that we can get to latest SNAPSHOT release of redis-om-spring:\n\n\n<repositories>\n  <repository>\n    <id>snapshots-repo</id>\n    <url>https://s01.oss.sonatype.org/content/repositories/snapshots/</url>\n  </repository>\n</repositories>\n\n\nAnd then in the `<dependencies>` section add version `0.3.0` of Redis OM Spring:\n\n\n<dependency>\n  <groupId>com.redis.om</groupId>\n  <artifactId>redis-om-spring</artifactId>\n  <version>0.3.0-SNAPSHOT</version>\n</dependency>"
    },
    {
      "id": "adding-swagger",
      "title": "Adding Swagger",
      "role": "content",
      "text": "We'll use the Swagger UI to test our web services endpoint. To add Swagger 2 to a Spring REST web service, using the Springfox implementation add the following dependencies to the POM:\n\n\n<dependency>\n  <groupId>io.springfox</groupId>\n  <artifactId>springfox-boot-starter</artifactId>\n  <version>3.0.0</version>\n</dependency>\n<dependency>\n  <groupId>io.springfox</groupId>\n  <artifactId>springfox-swagger-ui</artifactId>\n  <version>3.0.0</version>\n</dependency>\n\n\nLet's add Swagger Docker Bean to the Spring App class:\n\n\n@Bean\npublic Docket api() {\n  return new Docket(DocumentationType.SWAGGER_2)\n      .select()\n      .apis(RequestHandlerSelectors.any())\n      .paths(PathSelectors.any())\n      .build();\n}\n\n\nWhich will pick up any HTTP endpoints exposed by our application. Add to your app's property file (src/main/resources/application.properties):\n\n\nspring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER\n\n\nAnd finally, to enable Swagger on the application, we need to use the `EnableSwagger2` annotation, by\nannotating the main application class:\n\n\n@EnableSwagger2\n@SpringBootApplication\npublic class SkeletonApplication {\n  // ...\n}"
    },
    {
      "id": "creating-the-domain",
      "title": "Creating the Domain",
      "role": "content",
      "text": "Our domain will be fairly simple; `Person`s that have `Address`es. Let's start with the `Person` entity:\n\n\npackage com.redis.om.skeleton.models;\n\nimport java.util.Set;\n\nimport org.springframework.data.annotation.Id;\nimport org.springframework.data.geo.Point;\n\nimport com.redis.om.spring.annotations.Document;\nimport com.redis.om.spring.annotations.Indexed;\nimport com.redis.om.spring.annotations.Searchable;\n\nimport lombok.AccessLevel;\nimport lombok.AllArgsConstructor;\nimport lombok.Data;\nimport lombok.NonNull;\nimport lombok.RequiredArgsConstructor;\n\n@RequiredArgsConstructor(staticName = \"of\")\n@AllArgsConstructor(access = AccessLevel.PROTECTED)\n@Data\n@Document\npublic class Person {\n  // Id Field, also indexed\n  @Id\n  @Indexed\n  private String id;\n\n  // Indexed for exact text matching\n  @Indexed @NonNull\n  private String firstName;\n\n  @Indexed @NonNull\n  private String lastName;\n\n  //Indexed for numeric matches\n  @Indexed @NonNull\n  private Integer age;\n\n  //Indexed for Full Text matches\n  @Searchable @NonNull\n  private String personalStatement;\n\n  //Indexed for Geo Filtering\n  @Indexed @NonNull\n  private Point homeLoc;\n\n  // Nest indexed object\n  @Indexed @NonNull\n  private Address address;\n\n  @Indexed @NonNull\n  private Set<String> skills;\n}\n\n\nThe `Person` class has the following properties:\n\n* `id`: An autogenerated `String` using [ULIDs](https://github.com/ulid/spec)\n* `firstName`: A `String` representing their first or given name.\n* `lastName`: A `String` representing their last or surname.\n* `age`: An `Integer` representing their age in years.\n* `personalStatement`: A `String` representing a personal text statement containing facts or other biographical information.\n* `homeLoc`: A `org.springframework.data.geo.Point` representing the geo coordinates.\n* `address`: An entity of type `Address` representing the Person's postal address.\n* `skills`: A `Set<String>` representing a collection of Strings representing skills the Person possesses."
    },
    {
      "id": "document",
      "title": "@Document",
      "role": "content",
      "text": "The `Person` class (`com.redis.om.skeleton.models.Person`) is annotated with `@Document` (`com.redis.om.spring.annotations.Document`), which is marks the object as a Redis entity to be persisted as a JSON document by the appropriate type of repository."
    },
    {
      "id": "indexed-and-searchable",
      "title": "@Indexed and @Searchable",
      "role": "content",
      "text": "The fields `id`, `firstName`, `lastName`, `age`, `homeLoc`, `address`, and `skills` are all annotated\nwith `@Indexed` (`com.redis.om.spring.annotations.Indexed`). On entities annotated with `@Document` Redis OM Spring will scan the fields and add an appropriate search index field to the schema for the entity. For example, for the `Person` class\nan index named `com.redis.om.skeleton.models.PersonIdx` will be created on application startup. In the index schema, a search field will be added for each `@Indexed` annotated property. RediSearch, the underlying search engine powering searches, supports Text (full-text searches), Tag (exact-match searches), Numeric (range queries), Geo (geographic range queries), and Vector (vector queries) fields. For `@Indexed` fields, the appropriate search field (Tag, Numeric, or Geo) is selected based on the property's data type.\n\nFields marked as `@Searchable` (`com.redis.om.spring.annotations.Searchable`) such as `personalStatement` in `Person` are reflected as Full-Text search fields in the search index schema."
    },
    {
      "id": "nested-field-search-features",
      "title": "Nested Field Search Features",
      "role": "content",
      "text": "The embedded class `Address` (`com.redis.om.skeleton.models.Address`) has several properties annotated with `@Indexed`  and `@Searchable`, which will generate search index fields in Redis. The scanning of these fields is triggered by the `@Indexed` annotation on the `address` property in the `Person` class:\n\n\npackage com.redis.om.skeleton.models;\n\nimport com.redis.om.spring.annotations.Indexed;\nimport com.redis.om.spring.annotations.Searchable;\n\nimport lombok.Data;\nimport lombok.NonNull;\nimport lombok.RequiredArgsConstructor;\n\n@Data\n@RequiredArgsConstructor(staticName = \"of\")\npublic class Address {\n\n  @NonNull\n  @Indexed\n  private String houseNumber;\n\n  @NonNull\n  @Searchable(nostem = true)\n  private String street;\n\n  @NonNull\n  @Indexed\n  private String city;\n\n  @NonNull\n  @Indexed\n  private String state;\n\n  @NonNull\n  @Indexed\n  private String postalCode;\n\n  @NonNull\n  @Indexed\n  private String country;\n}"
    },
    {
      "id": "spring-data-repositories",
      "title": "Spring Data Repositories",
      "role": "content",
      "text": "With the model in place now, we need to create the bridge between the models and the Redis, a Spring Data Repository. Like other Spring Data Repositories, Redis OM Spring data repository's goal is to reduce the boilerplate code required to implement data access significantly. Create a Java interface like:\n\n\npackage com.redis.om.skeleton.models.repositories;\n\nimport com.redis.om.skeleton.models.Person;\nimport com.redis.om.spring.repository.RedisDocumentRepository;\n\npublic interface PeopleRepository extends RedisDocumentRepository<Person,String> {\n\n}\n\n\nThat's really all we need to get all the CRUD and Paging/Sorting functionality. The\n`RedisDocumentRepository` (`com.redis.om.spring.repository.RedisDocumentRepository`) extends `PagingAndSortingRepository` (`org.springframework.data.repository.PagingAndSortingRepository`) which extends CrudRepository to provide additional methods to retrieve entities using the pagination and sorting."
    },
    {
      "id": "enableredisdocumentrepositories",
      "title": "@EnableRedisDocumentRepositories",
      "role": "content",
      "text": "Before we can fire up the application, we need to enable our Redis Document repositories. Like most\nSpring Data projects, Redis OM Spring provides an annotation to do so; the `@EnableRedisDocumentRepositories`. We annotate the main application class:\n\n\n@EnableRedisDocumentRepositories(basePackages = \"com.redis.om.skeleton.*\")\n@EnableSwagger2\n@SpringBootApplication\npublic class SkeletonApplication {"
    },
    {
      "id": "crud-with-repositories",
      "title": "CRUD with Repositories",
      "role": "content",
      "text": "With the repositories enabled, we can use our repo; let's put in some data to see the object mapping in action. Let’s create `CommandLineRunner` that will execute on application startup:\n\n\npublic class SkeletonApplication {\n\n @Bean\n CommandLineRunner loadTestData(PeopleRepository repo) {\n   return args -> {\n     repo.deleteAll();\n\n     String thorSays = \"The Rabbit Is Correct, And Clearly The Smartest One Among You.\";\n\n     // Serendipity, 248 Seven Mile Beach Rd, Broken Head NSW 2481, Australia\n     Address thorsAddress = Address.of(\"248\", \"Seven Mile Beach Rd\", \"Broken Head\", \"NSW\", \"2481\", \"Australia\");\n\n     Person thor = Person.of(\"Chris\", \"Hemsworth\", 38, thorSays, new Point(153.616667, -28.716667), thorsAddress, Set.of(\"hammer\", \"biceps\", \"hair\", \"heart\"));\n\n     repo.save(thor);\n   };\n }\n\n\nIn the `loadTestData` method, we will take an instance of the `PeopleRepository` (thank you, Spring, for Dependency Injection!). Inside the returned lambda, we will first call the repo’s `deleteAll` method, which will ensure that we have clean data on each application reload.\n\nWe create a `Person` object using the Lombok generated builder method and then save it using the repo’s `save` method."
    },
    {
      "id": "keeping-tabs-with-redis-insight",
      "title": "Keeping tabs with Redis Insight",
      "role": "content",
      "text": "Let’s launch Redis Insight and connect to the localhost at port 6379. With a clean Redis Stack install, we can use the built-in CLI to check the keys in the system:\n\n![Redis Insight](./images/002_stack_spring.png \"Redis Insight\")\n\nFor a small amount of data, you can use the `keys` command (for any significant amount of data, use `scan`):\n\n\nkeys *\n\n\nIf you want to keep an eye on the commands issued against the server, Redis Insight provides a\nprofiler. If you click the \"profile\" button at the bottom of the screen, it should reveal the profiler window, and there you can start the profiler by clicking on the \"Start Profiler\" arrow.\n\nLet's start our Spring Boot application by using the Maven command:\n\n\n./mvnw spring-boot:run\n\n\nOn Redis Insight, if the application starts correctly, you should see a barrage of commands fly by on the profiler:\n\n![Redis Insight](./images/003_stack_spring.png \"Redis Insight\")\n\nNow we can inspect the newly loaded data by simply refreshing the \"Keys\" view:\n\n![Redis Insight](./images/004_stack_spring.png \"Redis Insight\")\n\nYou should now see two keys; one for the JSON document for \"Thor\" and one for the Redis Set that Spring Data Redis (and Redis OM Spring) use to maintain the list of primary keys for an entity.\n\nYou can select any of the keys on the key list to reveal their contents on the details panel. For JSON documents, we get a nice tree-view:\n\n![Redis Insight](./images/005_stack_spring.png \"Redis Insight\")\n\nSeveral Redis commands were executed on application startup. Let’s break them down so that we can understand what's transpired."
    },
    {
      "id": "index-creation",
      "title": "Index Creation",
      "role": "content",
      "text": "The first one is a call to [`FT.CREATE`](https://redis.io/docs/latest/commands/ft.create), which happens after Redis OM Spring scanned the `@Document` annotations. As you can see, since it encountered the annotation on `Person`, it creates the  `PersonIdx` index.\n\n\n\"FT.CREATE\"\n  \"com.redis.om.skeleton.models.PersonIdx\" \"ON\" \"JSON\"\n  \"PREFIX\" \"1\" \"com.redis.om.skeleton.models.Person:\"\n\"SCHEMA\"\n  \"$.id\" \"AS\" \"id\" \"TAG\"\n  \"$.firstName\" \"AS\" \"firstName\" \"TAG\"\n  \"$.lastName\" \"AS\" \"lastName\" \"TAG\"\n  \"$.age\" \"AS\" \"age\" \"NUMERIC\"\n  \"$.personalStatement\" \"AS\" \"personalStatement\" \"TEXT\"\n  \"$.homeLoc\" \"AS\" \"homeLoc\" \"GEO\"\n  \"$.address.houseNumber\" \"AS\" \"address_houseNumber\" \"TAG\"\n  \"$.address.street\" \"AS\" \"address_street\" \"TEXT\" \"NOSTEM\"\n  \"$.address.city\" \"AS\" \"address_city\" \"TAG\"\n  \"$.address.state\" \"AS\" \"address_state\" \"TAG\"\n  \"$.address.postalCode\" \"AS\" \"address_postalCode\" \"TAG\"\n  \"$.address.country\" \"AS\" \"address_country\" \"TAG\"\n  \"$.skills[*]\" \"AS\" \"skills\""
    },
    {
      "id": "cleaning-the-person-repository",
      "title": "Cleaning the Person Repository",
      "role": "content",
      "text": "The next set of commands are generated by the call to `repo.deleteAll()`:\n\n\n\"DEL\" \"com.redis.om.skeleton.models.Person\"\n\"KEYS\" \"com.redis.om.skeleton.models.Person:*\"\n\n\nThe first call clears the set of Primary Keys that Spring Data Redis maintains (and therefore Redis OM Spring), the second call collects all the keys to delete them, but there are none to delete on this first load of the data."
    },
    {
      "id": "saving-person-entities",
      "title": "Saving Person Entities",
      "role": "content",
      "text": "The next repo call is `repo.save(thor)` that triggers the following sequence:\n\n\n\"SISMEMBER\" \"com.redis.om.skeleton.models.Person\" \"01FYANFH68J6WKX2PBPX21RD9H\"\n\"EXISTS\" \"com.redis.om.skeleton.models.Person:01FYANFH68J6WKX2PBPX21RD9H\"\n\"JSON.SET\" \"com.redis.om.skeleton.models.Person:01FYANFH68J6WKX2PBPX21RD9H\" \".\" \"{\"id\":\"01FYANFH68J6WKX2PBPX21RD9H\",\"firstName\":\"Chris\",\"lastName\":\"Hemsworth\",\"age\":38,\"personalStatement\":\"The Rabbit Is Correct, And Clearly The Smartest One Among You.\",\"homeLoc\":\"153.616667,-28.716667\",\"address\":{\"houseNumber\":\"248\",\"street\":\"Seven Mile Beach Rd\",\"city\":\"Broken Head\",\"state\":\"NSW\",\"postalCode\":\"2481\",\"country\":\"Australia\"},\"skills\":[\"biceps\",\"hair\",\"heart\",\"hammer\"]}\n\"SADD\" \"com.redis.om.skeleton.models.Person\" \"01FYANFH68J6WKX2PBPX21RD9H\"\n\n\nLet's break it down:\n\n* The first call uses the generated ULID to check if the id is in the set of primary keys (if it is, it’ll be removed)\n* The second call checks if JSON document exists (if it is, it’ll be removed)\n* The third call uses the [`JSON.SET`](https://redis.io/docs/latest/commands/json.set) command to save the JSON payload\n* The last call adds the primary key of the saved document to the set of primary keys\n\nNow that we’ve seen the repository in action via the `.save` method, we know that the trip from Java to Redis work. Now let’s add some more data to make the interactions more interesting:\n\n\n@Bean\nCommandLineRunner loadTestData(PeopleRepository repo) {\n  return args -> {\n    repo.deleteAll();\n\n    String thorSays = \"The Rabbit Is Correct, And Clearly The Smartest One Among You.\";\n    String ironmanSays = \"Doth mother know you weareth her drapes?\";\n    String blackWidowSays = \"Hey, fellas. Either one of you know where the Smithsonian is? I’m here to pick up a fossil.\";\n    String wandaMaximoffSays = \"You Guys Know I Can Move Things With My Mind, Right?\";\n    String gamoraSays = \"I Am Going To Die Surrounded By The Biggest Idiots In The Galaxy.\";\n    String nickFurySays = \"Sir, I’m Gonna Have To Ask You To Exit The Donut\";\n\n    // Serendipity, 248 Seven Mile Beach Rd, Broken Head NSW 2481, Australia\n    Address thorsAddress = Address.of(\"248\", \"Seven Mile Beach Rd\", \"Broken Head\", \"NSW\", \"2481\", \"Australia\");\n\n    // 11 Commerce Dr, Riverhead, NY 11901\n    Address ironmansAddress = Address.of(\"11\", \"Commerce Dr\", \"Riverhead\", \"NY\",  \"11901\", \"US\");\n\n    // 605 W 48th St, New York, NY 10019\n    Address blackWidowAddress = Address.of(\"605\", \"48th St\", \"New York\", \"NY\", \"10019\", \"US\");\n\n    // 20 W 34th St, New York, NY 10001\n    Address wandaMaximoffsAddress = Address.of(\"20\", \"W 34th St\", \"New York\", \"NY\", \"10001\", \"US\");\n\n    // 107 S Beverly Glen Blvd, Los Angeles, CA 90024\n    Address gamorasAddress = Address.of(\"107\", \"S Beverly Glen Blvd\", \"Los Angeles\", \"CA\", \"90024\", \"US\");\n\n    // 11461 Sunset Blvd, Los Angeles, CA 90049\n    Address nickFuryAddress = Address.of(\"11461\", \"Sunset Blvd\", \"Los Angeles\", \"CA\", \"90049\", \"US\");\n\n    Person thor = Person.of(\"Chris\", \"Hemsworth\", 38, thorSays, new Point(153.616667, -28.716667), thorsAddress, Set.of(\"hammer\", \"biceps\", \"hair\", \"heart\"));\n    Person ironman = Person.of(\"Robert\", \"Downey\", 56, ironmanSays, new Point(40.9190747, -72.5371874), ironmansAddress, Set.of(\"tech\", \"money\", \"one-liners\", \"intelligence\", \"resources\"));\n    Person blackWidow = Person.of(\"Scarlett\", \"Johansson\", 37, blackWidowSays, new Point(40.7215259, -74.0129994), blackWidowAddress, Set.of(\"deception\", \"martial_arts\"));\n    Person wandaMaximoff = Person.of(\"Elizabeth\", \"Olsen\", 32, wandaMaximoffSays, new Point(40.6976701, -74.2598641), wandaMaximoffsAddress, Set.of(\"magic\", \"loyalty\"));\n    Person gamora = Person.of(\"Zoe\", \"Saldana\", 43, gamoraSays, new Point(-118.399968, 34.073087), gamorasAddress, Set.of(\"skills\", \"martial_arts\"));\n    Person nickFury = Person.of(\"Samuel L.\", \"Jackson\", 73, nickFurySays, new Point(-118.4345534, 34.082615), nickFuryAddress, Set.of(\"planning\", \"deception\", \"resources\"));\n\n    repo.saveAll(List.of(thor, ironman, blackWidow, wandaMaximoff, gamora, nickFury));\n  };\n}\n\n\nWe have 6 People in the database now; since we’re using the devtools in Spring, the app should have reloaded, and the database reseeded with new data. Press enter the key pattern input box in Redis Insight to refresh the view. Notice that we used the repository’s `saveAll` to save several objects in bulk.\n\n![Redis Insight](./images/006_stack_spring.png \"Redis Insight\")"
    },
    {
      "id": "web-service-endpoints",
      "title": "Web Service Endpoints",
      "role": "content",
      "text": "Before we beef up the repository with more interesting queries, let’s create a controller so that we can test our queries using the Swagger UI:\n\n\npackage com.redis.om.skeleton.controllers;\n\nimport com.redis.om.skeleton.models.Person;\nimport com.redis.om.skeleton.models.repositories.PeopleRepository;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\n@RequestMapping(\"/api/v1/people\")\npublic class PeopleControllerV1 {\n @Autowired\n PeopleRepository repo;\n\n @GetMapping(\"all\")\n Iterable<Person> all() {\n   return repo.findAll();\n }\n}\n\n\nIn this controller, we inject a repository and use one of the CRUD methods, `findAll()`, to return all the `Person` documents in the database.\n\nIf we navigate to http://localhost:8080/swagger-ui/ you should see the Swagger UI:\n\n![SwaggerUI](./images/007_stack_spring.png \"SwaggerUI\")\n\nWe can see the `/all` method from our people-controller-v-1, expanding that you should see:\n\n![SwaggerUI](./images/008_stack_spring.png \"SwaggerUI\")\n\nAnd if you select \"Try it out\" and then \"Execute,\" you should see the resulting JSON array containing all People documents in the database:\n\n![SwaggerUI](./images/009_stack_spring.png \"SwaggerUI\")\n\nLet’s also add the ability to retrieve a Person by its id by using the repo’s findById method:\n\n\n@GetMapping(\"{id}\")\nOptional<Person> byId(@PathVariable String id) {\n  return repo.findById(id);\n}\n\n\nRefreshing the Swagger UI, we should see the newly added endpoint. We can grab an id using the [`SRANDMEMBER`](https://redis.io/docs/latest/commands/srandmember) command on the Redis Insight CLI like this:\n\n\nSRANDMEMBER com.redis.om.skeleton.models.Person\n\n\nPlugging the resulting ID in the Swagger UI, we can get the corresponding  JSON document:\n\n![SwaggerUI](./images/010_stack_spring.png \"SwaggerUI\")"
    },
    {
      "id": "custom-repository-finders",
      "title": "Custom Repository Finders",
      "role": "content",
      "text": "Now that we tested quite a bit of the CRUD functionality, let's add some custom finders to our repository. We’ll start with a finder over a numeric range, on the `age` property of `Person`:\n\n\npublic interface PeopleRepository extends RedisDocumentRepository<Person,String> {\n // Find people by age range\n Iterable<Person> findByAgeBetween(int minAge, int maxAge);\n}\n\n\nAt runtime, the repository method `findByAgeBetween` is fulfilled by the framework, so all you need to do is declare it, and Redis OM Spring will handle the querying and mapping of the results. The property or properties to be used are picked after the key phrase \"findBy\". The \"Between\" keyword is the predicate that tells the query builder what operation to use.\n\nTo test it on the Swagger UI, let’s add a corresponding method to the controller:\n\n\n@GetMapping(\"age_between\")\nIterable<Person> byAgeBetween( //\n    @RequestParam(\"min\") int min, //\n    @RequestParam(\"max\") int max) {\n  return repo.findByAgeBetween(min, max);\n}\n\n\nRefreshing the UI, we can see the new endpoint. Let’s try it with some data:\n\n![SwaggerUI](./images/011_stack_spring.png \"SwaggerUI\")\n\nInvoke the endpoint with the value `30` for `min` and `37` for `max` we get two hits;\n\"Scarlett Johansson\" and \"Elizabeth Olsen\" are the only two people with ages between 30 and 37.\n\n![SwaggerUI](./images/012_stack_spring.png \"SwaggerUI\")\n\nIf we look at the Redis Insight Profiler, we can see the resulting query, which is a range query on the index numeric field `age`:\n\n![Redis Insight](./images/013_stack_spring.png \"Redis Insight Profiler\")\n\nWe can also create query methods with more than one property. For example, if we wanted to do a query by first and last names, we would declare a repository method like:\n\n\n// Find people by their first and last name\nIterable<Person> findByFirstNameAndLastName(String firstName, String lastName);\n\n\nLet’s add a corresponding controller method:\n\n\n@GetMapping(\"name\")\nIterable<Person> byFirstNameAndLastName(@RequestParam(\"first\") String firstName, //\n    @RequestParam(\"last\") String lastName) {\n  return repo.findByFirstNameAndLastName(firstName, lastName);\n}\n\n\nOnce again, we can refresh the swagger UI and test the newly created endpoint:\n\n![SwaggerUI](./images/014_stack_spring.png \"SwaggerUI\")\n\nExecuting the request with the first name `Robert` and last name `Downey`, we get:\n\n![SwaggerUI](./images/015_stack_spring.png \"SwaggerUI\")\n\nAnd the resulting query on Redis Insight:\n\n![Redis Insight](./images/016_stack_spring.png \"Redis Insight Profiler\")\n\nNow let’s try a Geospatial query. The `homeLoc` property is a Geo Point, and by using the \"Near\" predicate in our method declaration, we can get a finder that takes a point and a radius around that point to search:\n\n\n// Draws a circular geofilter around a spot and returns all people in that\n// radius\nIterable<Person> findByHomeLocNear(Point point, Distance distance);\nAnd the corresponding controller method:\n\n@GetMapping(\"homeloc\")\nIterable<Person> byHomeLoc(//\n    @RequestParam(\"lat\") double lat, //\n    @RequestParam(\"lon\") double lon, //\n    @RequestParam(\"d\") double distance) {\n  return repo.findByHomeLocNear(new Point(lon, lat), new Distance(distance, Metrics.MILES));\n}\n\n\nRefreshing the Swagger US, we should now see the `byHomeLoc` endpoint. Let’s see which of the Avengers live within 10 miles of Suffolk Park Pub in South Wales, Australia... hmmm.\n\n![SwaggerUI](./images/017_stack_spring.png \"SwaggerUI\")\n\nExecuting the request, we get the record for Chris Hemsworth:\n\n![SwaggerUI](./images/018_stack_spring.png \"SwaggerUI\")\n\nand in Redis Insight we can see the backing query:\n\n![Redis Insight](./images/019_stack_spring.png \"Redis Insight Profiler\")\n\nLet’s try a full-text search query against the `personalStatement` property. To do so, we prefix our query method with the word `search` as shown below:\n\n\n// Performs full-text search on a person’s personal Statement\nIterable<Person> searchByPersonalStatement(String text);\n\n\nAnd the corresponding controller method:\n\n\n@GetMapping(\"statement\")\nIterable<Person> byPersonalStatement(@RequestParam(\"q\") String q) {\n  return repo.searchByPersonalStatement(q);\n}\n\n\nOnce again, we can try it on the Swagger UI with the text \"mother\":\n\n![SwaggerUI](./images/020_stack_spring.png \"SwaggerUI\")\n\nWhich results in a single hit, the record for Robert Downey Jr.:\n\n![SwaggerUI](./images/021_stack_spring.png \"SwaggerUI\")\n\nNotice that you can pass a query string like \"moth*\" with wildcards if needed\n\n![SwaggerUI](./images/022_stack_spring.png \"SwaggerUI\")"
    },
    {
      "id": "nested-object-searches",
      "title": "Nested object searches",
      "role": "content",
      "text": "You’ve noticed that the `address` object in `Person` is mapped as a JSON object. If we want to search by address fields, we use an underscore to access the nested fields. For example, if we wanted to find a Person by their city, the method signature would be:\n\n\n// Performing a tag search on city\nIterable<Person> findByAddress_City(String city);\n\n\nLet’s add the matching controller method so that we can test it:\n\n\n@GetMapping(\"city\")\nIterable<Person> byCity(@RequestParam(\"city\") String city) {\n  return repo.findByAddress_City(city);\n}\n\n\nLet’s test the byCity endpoint:\n\n![SwaggerUI](./images/023_stack_spring.png \"SwaggerUI\")\n\nAs expected, we should get two hits; Scarlett Johansson and Elizabeth Olsen, both with addresses in Nee York:\n\n![SwaggerUI](./images/024_stack_spring.png \"SwaggerUI\")\n\nThe skills set is indexed as tag search. To find a Person with any of the skills in a provided list, we can add a repository method like:\n\n\n// Search Persons that have one of multiple skills (OR condition)\nIterable<Person> findBySkills(Set<String> skills);\n\n\nAnd the corresponding controller method:\n\n\n@GetMapping(\"skills\")\nIterable<Person> byAnySkills(@RequestParam(\"skills\") Set<String> skills) {\n  return repo.findBySkills(skills);\n}\n\n\nLet's test the endpoint with the value \"deception\":\n\n![SwaggerUI](./images/025_stack_spring.png \"SwaggerUI\")\n\nThe search returns the records for Scarlett Johansson and Samuel L. Jackson:\n\n![SwaggerUI](./images/026_stack_spring.png \"SwaggerUI\")\n\nWe can see the backing query using a tag search:\n\n![Redis Insight](./images/027_stack_spring.png \"Redis Insight Profiler\")"
    },
    {
      "id": "fluid-searching-with-entity-streams",
      "title": "Fluid Searching with Entity Streams",
      "role": "content",
      "text": "Redis OM Spring Entity Streams provides a Java 8 Streams interface to Query Redis JSON documents using Redis Stack. Entity Streams allow you to process data in a typesafe declarative way similar to SQL statements. Streams can be used to express a query as a chain of operations.\n\nEntity Streams in Redis OM Spring provide the same semantics as Java 8 streams. Streams can be made of Redis Mapped entities (`@Document`) or one or more properties of an Entity. Entity Streams progressively build the query until a terminal operation is invoked (such as `collect`). Whenever a Terminal operation is applied to a Stream, the Stream cannot accept additional operations to its pipeline, which means that the Stream is started.\n\nLet’s start with a simple example, a Spring `@Service` which includes `EntityStream` to query for instances of the mapped class `Person`:\n\n\npackage com.redis.om.skeleton.services;\n\nimport java.util.stream.Collectors;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\n\nimport com.redis.om.skeleton.models.Person;\nimport com.redis.om.skeleton.models.Person$;\nimport com.redis.om.spring.search.stream.EntityStream;\n\n@Service\npublic class PeopleService {\n  @Autowired\n  EntityStream entityStream;\n\n  // Find all people\n  public Iterable<Person> findAllPeople(int minAge, int maxAge) {\n    return entityStream //\n        .of(Person.class) //\n        .collect(Collectors.toList());\n  }\n\n}\n\n\nThe `EntityStream` is injected into the `PeopleService` using `@Autowired`. We can then get a stream for `Person` objects by using `entityStream.of(Person.class)`. The stream represents the equivalent of a `SELECT * FROM Person` on a relational database. The call to `collect` will then execute the underlying query and return a collection of all `Person` objects in Redis."
    },
    {
      "id": "entity-meta-model",
      "title": "Entity Meta-model",
      "role": "content",
      "text": "You’re provided with a generated meta-model to produce more elaborate queries, a class with the same name as your model but ending with a dollar sign. In the\nexample below, our entity model is `Person`; therefore, we get a meta-model named `Person$`. With the meta-model, you have access to the\nunderlying search engine field operations. For example, we have an `age` property which is an integer. Therefore our meta-model has an `AGE` property with\nnumeric operations we can use with the stream’s `filter` method such as `between`.\n\n\n// Find people by age range\npublic Iterable<Person> findByAgeBetween(int minAge, int maxAge) {\n  return entityStream //\n      .of(Person.class) //\n      .filter(Person$.AGE.between(minAge, maxAge)) //\n      .sorted(Person$.AGE, SortOrder.ASC) //\n      .collect(Collectors.toList());\n}\n\n\nIn this example, we also use the Streams `sorted` method to declare that our stream will be sorted by the `Person$.AGE` in `ASC`ending order.\n\nTo \"AND\" property expressions we can chain multiple `.filter` statements. For example, to recreate\nthe finder by first and last name we can use an Entity Stream in the following way:\n\n\n// Find people by their first and last name\npublic Iterable<Person> findByFirstNameAndLastName(String firstName, String lastName) {\n  return entityStream //\n      .of(Person.class) //\n      .filter(Person$.FIRST_NAME.eq(firstName)) //\n      .filter(Person$.LAST_NAME.eq(lastName)) //\n      .collect(Collectors.toList());\n}\n\n\nIn this article, we explored how Redis OM Spring provides a couple of APIs to tap into the power of Redis Stack’s document database and search features from Spring Boot application. We’ll explore other Redis Stack features via Redis OM Spring in future articles"
    }
  ],
  "examples": []
}
