DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Spring Cloud Sleuth + RabbitMQ + Zipkin + ElasticSearch
  • Introduction to Spring Data Elasticsearch 4.1
  • Spring Boot Application With Kafka, Elasticsearch, Redis With Enterprise Standards Part 1
  • Sprinkle Some ELK on Your Spring Boot Logs

Trending

  • The Full-Stack Developer's Blind Spot: Why Data Cleansing Shouldn't Be an Afterthought
  • Metrics at a Glance for Production Clusters
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 2
  • MySQL to PostgreSQL Database Migration: A Practical Case Study
  1. DZone
  2. Coding
  3. Frameworks
  4. Bulk Indexing With ElasticSearch

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.

By 
Cagatay Gokcel user avatar
Cagatay Gokcel
·
Dec. 28, 16 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
31.1K Views

Join the DZone community and get the full member experience.

Join For Free

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/.

Elasticsearch Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • Spring Cloud Sleuth + RabbitMQ + Zipkin + ElasticSearch
  • Introduction to Spring Data Elasticsearch 4.1
  • Spring Boot Application With Kafka, Elasticsearch, Redis With Enterprise Standards Part 1
  • Sprinkle Some ELK on Your Spring Boot Logs

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!