Technology Sharing

Elasticsearch 8.14.1 and Spring Data Elasticsearch Example Demonstration

2024-07-08

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Create project and configuration

Implement three types of APIs.

  1. Search by name
  2. Search by category
  3. According to price range

Create a spring boot project and add elasticsearch dependency

Configure Elasticsearch

@Configuration
@EnableElasticsearchRepositories(basePackages = "github.io.truongbn.elasticsearch.repository")
public class ClientConfig extends ElasticsearchConfiguration {
   
    @Override
    public ClientConfiguration clientConfiguration() {
   
        return ClientConfiguration.builder()
                .connectedTo("192.168.163.13:9200")
                .withBasicAuth("elastic","123456")
                .build();
    }
}

More configuration reference addresses

Object Mapping

Spring Data Elasticsearch can map objects to JSON and store them in ES, or it can convert them into objects.

@Data
@Document(indexName = "itemindex")
public class Item {
   
    @Id
    private int id;
    @Field(type = FieldType.Text, name = "name")
    private String name;
    @Field(type = FieldType.Double, name = "price")
    private Double price;
    @Field(type = FieldType.Keyword, name = "brand")
    private String brand;
    @Field(type = FieldType.Keyword, name = "category")
    private String category;
}
  • @Document: Store the class object in the index named itemindex
  • @Id: Ensure that doc is unique in the index.
  • @Field: Define or map fields in doc

More about object mapping reference: Elasticsearch Object Mapping

Elasticsearch Repositories

Integrate the ElasticsearchRepository class and inherit itsave(), saveAll(),findAll()ElasticsearchRepository generates queries based on method names.

public interface ItemRepository 
        extends ElasticsearchRepository