Saturday, 7 December 2019

Spring boot: MongoDB: Create index


MongoDB provides several annotations to create an index.
a.   @Indexed: Mark a field to be indexed using MongoDB's indexing feature.
b.   @TextIndexed: Mark a field to be part of the text index. As there can be only one text index per collection. All fields marked with TextIndexed are combined into one single index.
c.    @CompoundIndex: Mark a class to use compound indexes.
d.   @GeoSpatialIndexed: Mark a field to be indexed using MongoDB's geospatial indexing feature.

Let's create an index on employee firstName field using @Index annotation.
@Document("employees")
public class Employee {

 @Indexed(name="emp_first_name", direction = IndexDirection.ASCENDING)
 private String firstName;

 ......
 ......
}

Find the below working application.


Address.java
package com.sample.app.entity;

public class Address {
 private String city;
 private String country;

 public Address(String city, String country) {
  this.city = city;
  this.country = country;
 }

 public String getCity() {
  return city;
 }

 public void setCity(String city) {
  this.city = city;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Address [city=").append(city).append(", country=").append(country).append("]");
  return builder.toString();
 }

}


Employee.java
package com.sample.app.entity;

import java.util.List;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.IndexDirection;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

@Document("employees")
public class Employee {
 @Id
 private String id;

 @Indexed(name="emp_first_name", direction = IndexDirection.ASCENDING)
 private String firstName;

 private String lastName;

 private List<Address> addresses;

 public Employee() {
 }

 public Employee(String firstName, String lastName, List<Address> addresses) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.addresses = addresses;
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
    .append(lastName).append(", addresses=").append(addresses).append("]");
  return builder.toString();
 }

}


EmployeeRepository.java
package com.sample.app.repository;

import java.util.List;
import java.util.stream.Stream;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;

import com.sample.app.entity.Employee;

@Repository
public interface EmployeeRepository extends MongoRepository<Employee, String> {
 List<Employee> findByFirstName(String firstName);
 
 List<Employee> findByLastName(String lastName);
 
 List<Employee> findByFirstNameAndLastName(String firstName, String lastName);
 
 @Query("{'firstName' : ?0}")
 Stream<Employee> findAllByCustomQueryAndStream(String firstName);
}


application.properties
spring.data.mongodb.database=myorg
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost

logging.level.org.springframework.data=WARN


pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>springDataMongo</groupId>
 <artifactId>springDataMongo</artifactId>
 <version>1</version>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.6.RELEASE</version>
 </parent>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-mongodb</artifactId>
  </dependency>
 </dependencies>
</project>


App.java
package com.sample.app;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;

import com.mongodb.MongoClient;
import com.sample.app.entity.Address;
import com.sample.app.entity.Employee;
import com.sample.app.repository.EmployeeRepository;

@SpringBootApplication
public class App {
 @Value("${spring.data.mongodb.database}")
 private String database;

 @Value("${spring.data.mongodb.host}")
 private String host;

 @Value("${spring.data.mongodb.port}")
 private int port;

 @Autowired
 private EmployeeRepository empRepository;

 public static void main(String[] args) {

  SpringApplication.run(App.class, args);
 }

 public void dropPreviousData() {
  MongoClient mongoClient = new MongoClient(host, port);

  MongoOperations mongoOps = new MongoTemplate(mongoClient, database);

  mongoOps.dropCollection("employees");
 }

 @Bean
 public CommandLineRunner demo() {
  return (args) -> {

   dropPreviousData();

   MongoClient mongoClient = new MongoClient(host, port);
   MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, database);

   List<Address> emp1Addresses = Arrays.asList(new Address("Bangalore", "India"),
     new Address("Hyderabad", "India"));
   List<Address> emp2Addresses = Arrays.asList(new Address("Hyderabad", "India"));
   List<Address> emp3Addresses = Arrays.asList(new Address("Chennai", "India"),
     new Address("Hyderabad", "India"));
   List<Address> emp4Addresses = Arrays.asList(new Address("Amaravathi", "India"),
     new Address("Ongole", "India"));

   Employee emp1 = new Employee("Phalgun", "Garimella", emp1Addresses);
   Employee emp2 = new Employee("Sankalp", "Dubey", emp2Addresses);
   Employee emp3 = new Employee("Arpan", "Garimella", emp3Addresses);
   Employee emp4 = new Employee("Phalgun", "Dubey", emp4Addresses);

   mongoTemplate.save(emp1);
   mongoTemplate.save(emp2);
   mongoTemplate.save(emp3);
   mongoTemplate.save(emp4);

   List<Employee> emps = empRepository.findByFirstName("Phalgun");
   emps.forEach(System.out::println);

  };
 }
}


Total project structure looks like below.


Run App.java, you can see below messages in console.
Employee [id=5d53c36898c4b259e39a2c26, firstName=Phalgun, lastName=Garimella, addresses=[Address [city=Bangalore, country=India], Address [city=Hyderabad, country=India]]]
Employee [id=5d53c36898c4b259e39a2c29, firstName=Phalgun, lastName=Dubey, addresses=[Address [city=Amaravathi, country=India], Address [city=Ongole, country=India]]]


You can download complete working application from this link.

Previous                                                    Next                                                    Home

1 comment:

  1. Hello Team,
    Need input how to auto create Index with spring boot application connecting with Azure Cosmos DB(Mongo API).
    Application Details
    1. Below are dependencies defined
    buildscript {
    ext {
    springBootVersion = '2.0.0.RELEASE'
    }
    dependencies {
    classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
    }
    implementation 'org.springframework.boot:spring-boot-starter-undertow'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
    implementation 'org.springframework.boot:spring-boot-starter-cloud-connectors'
    implementation 'org.springframework.boot:spring-boot-starter-data-rest'
    implementation 'org.springframework.cloud:spring-cloud-starter-config:2.0.0.RELEASE'
    2. Mongo DB driver
    implementation ('org.mongodb:mongo-java-driver:3.4.2') {
    force = true
    }
    In the pojo model, annotate @indexed on the property(for which, index to be created) and model is decorated with @document. No explicit code for mapping or creating the document.
    public class MongoConfiguration extends AbstractCloudConfig { @Bean public MongoDbFactory mongoDbFactory() { return connectionFactory().mongoDbFactory(); } }
    My understanding is that Auto creation of index is disabled by default.
    What changes are required to enable the index creation. Any suggestions would be great help.

    ReplyDelete