Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Bulk Indexing With ElasticSearch

DZone's Guide to

Bulk Indexing With ElasticSearch

If your case requires a lot of document indexing, then extensive care should be taken to speed up the process. bulkIndex can help.

Free Resource

Evolve your approach to Application Performance Monitoring by adopting five best practices that are outlined and explored in this e-book, brought to you in partnership with BMC.

We recently developed a search engine with Java that can index and do full-text searches on documents. If your case requires too much document indexing, then extensive care should be taken in terms of the performance of the ElasticSearch indexing process. In such situations, you should use bulkIndex method to speed up the process. Bulk sizing is dependent on your data and cluster configuration, but the general approach recommends 5 to 15 MB per bulk.

Let's create a Spring Boot project that can index documents with ElasticSearch.

<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>com.es</groupId>
<artifactId>bulkIndexExample</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>BulkIndexExample</name>
<description>Example of spring elasticsearch bulk indexing</description>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
 <groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
 <version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

First, we need to configure applicationContext.xml as shown below. Our sample application starts ElasticSearch as an embedded server. We don't need to install an external ElasticSearch server.

<elasticsearch:node-client id="client" local="true" />

<bean name="elasticsearchTemplate"
class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client" />
</bean>

We can change the ElasticSearch port on application.properties. Also, you can enable spring-data repository features for ElasticSearch using this property.

spring.data.elasticsearch.repositories.enabled = true
application.properties
spring.data.elasticsearch.cluster-nodes=localhost:9300
spring.data.elasticsearch.repositories.enabled=true
spring.data.elasticsearch.properties.node.local=true

We need to define domain entities and a repository class for Spring data crud support.

Define your identifier field with an @Id annotation. If you do not specify the ID field, ElasticSearch can't index your document.

We need to specify indexName and type for our document.@Document annotation also helps to us set shard and replica count.

@Document(indexName = "carIndex", type = "carType", shards = 1, replicas = 0)
    private class Car implements Serializable {

        @Id
        private Long id;
        private String brand;
        private String model;
        private BigDecimal amount;

        public Car(Long id, String brand, String model, BigDecimal amount) {
            this.id = id;
            this.brand = brand;
            this.model = model;
            this.amount = amount;
        }

        public Long getId() {
            return id;
        }

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

        public String getBrand() {
            return brand;
        }

        public void setBrand(String brand) {
            this.brand = brand;
        }

        public String getModel() {
            return model;
        }

        public void setModel(String model) {
            this.model = model;
        }

        public BigDecimal getAmount() {
            return amount;
        }

        public void setAmount(BigDecimal amount) {
            this.amount = amount;
        }
    }

Let's define an IndexerService and index documents with bulk requests. First, check if the index exists on ElasticSearch. If it does not exist, you should create one.

ElasticsearchTemplate accepts the IndexQuery list to index your documents.

When indexing process finished, we can refresh our index. 

@Service
public class IndexerService {
    private  static  final  String CAR_INDEX_NAME = "car_index";
    private  static  final  String CAR_INDEX_TYPE = "car_type";

    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;

    public long bulkIndex() throws Exception {

        int counter = 0;

        try {
            if (!elasticsearchTemplate.indexExists(CAR_INDEX_NAME)) {
                elasticsearchTemplate.createIndex(CAR_INDEX_NAME);
            }
            Gson gson = new Gson();
            List<IndexQuery> queries = new ArrayList<IndexQuery>();
            List<Car> cars = createTestData();
            for (Car car : cars) {
                IndexQuery indexQuery = new IndexQuery();
                indexQuery.setId(car.getId().toString());
                indexQuery.setSource(gson.toJson(car));
                indexQuery.setIndexName(CAR_INDEX_NAME);
                indexQuery.setType(CAR_INDEX_TYPE);

                queries.add(indexQuery);
                if (counter % Constants.INDEX_COMMIT_SIZE == 0) {
                    elasticsearchTemplate.bulkIndex(queries);
                    queries.clear();
                    System.out.println("bulkIndex counter : " + counter);
                }
                counter++;
            }
            if (queries.size() > 0) {
                elasticsearchTemplate.bulkIndex(queries);
            }

            elasticsearchTemplate.refresh(CAR_INDEX_NAME, true);
            System.out.println("bulkIndex completed.");

        } catch (Exception e) {
            System.out.println("IndexerService.bulkIndex e;" + e.getMessage());
            throw e;
        }
        return -1;
    }

    private List<Car> createTestData() {
        List<Car> cars = new ArrayList<Car>();
        cars.add(new Car(Long.valueOf(123), "Seat", "Leon",BigDecimal.valueOf(78000)));
        cars.add(new Car(Long.valueOf(124), "Seat", "Rio",BigDecimal.valueOf(62000)));
        cars.add(new Car(Long.valueOf(125), "Kia", "Ceed",BigDecimal.valueOf(80000)));
        cars.add(new Car(Long.valueOf(126), "Mazda", "3",BigDecimal.valueOf(80000)));
        cars.add(new Car(Long.valueOf(127), "Volkswagen", "Polo",BigDecimal.valueOf(72000)));
        cars.add(new Car(Long.valueOf(128), "Volkswagen", "Golf",BigDecimal.valueOf(98000)));
        cars.add(new Car(Long.valueOf(129), "Volkswagen", "Tiguan",BigDecimal.valueOf(120000)));
        cars.add(new Car(Long.valueOf(130), "Opel", "Astra",BigDecimal.valueOf(80000)));
        cars.add(new Car(Long.valueOf(131), "Opel", "Corsa",BigDecimal.valueOf(70000)));
        return cars;
    }
}

Create a Spring boot main class and import the applicationContext resource.

@Configuration
@ComponentScan
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@SpringBootApplication
@ImportResource("classpath:applicationContext.xml")
public class App extends SpringBootServletInitializer {

  public static void main(String[] args) throws Exception {
    SpringApplication.run(App.class, args);
  }
}

Create a CommandLineRunner class and call the bulkIndex method.

@Component
public class AppLoader implements CommandLineRunner {

    @Autowired
    IndexerService indexerService;

    @Override
    public void run(String... strings) throws Exception {
        indexerService.bulkIndex();
    }

}

You can check index results from this URL: localhost:9200/car_index/_search/.

Evolve your approach to Application Performance Monitoring by adopting five best practices that are outlined and explored in this e-book, brought to you in partnership with BMC.

Topics:
elasticsearch ,tutorial ,bulk indexing ,performance ,java

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}