Environment
1.elasticsearch 7.8.0
2.springboot 2.4.0
3.JDK 8
Integrated configuration
1.pom.xml
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.0</version> </parent> <dependencies> <!-- ES dependencies --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-test</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies>
2.application.yml
# The ES configuration file will read the host and port here to create an ES connection object. elasticsearch: host: 127.0.0.1 port: 9200
3.ElasticSearch configuration file
/** * ElasticSearch configuration file, used to obtain ES connection objects */ import lombok.Data; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration; @ConfigurationProperties(value = "elasticsearch") // Match the configuration starting with elasticsearch in application.yml, and assign values to the following host and port @Configuration @Data public class ElasticsearchConfig extends AbstractElasticsearchConfiguration { private String host; private Integer port; @Override public RestHighLevelClient elasticsearchClient() { RestClientBuilder builder = RestClient.builder(new HttpHost(host, port)); RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder); return restHighLevelClient; } }
4. Define ElasticSearch entities
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; @Data @AllArgsConstructor @NoArgsConstructor @Document(indexName = "product", shards = 3, replicas = 1) // indexName specifies the index name, shards specifies the number of index shards, replicas specifies the number of shards public class Product { @Id private Long id; /* ID */ @Field(type = FieldType.Text,analyzer = "ik_max_word") /* text word segmentation, analyzer = "ik_max_word" specifies the word segmentation type */ private String title; /* title */ @Field(type = FieldType.Keyword) /* keyword without word segmentation */ private String category; /* brand */ @Field(type = FieldType.Double) private Double price; /* price */ @Field(type = FieldType.Keyword, index = false) // index = false means that images query cannot be used private String images; /* pictures */ }
5. Define the data persistence layer Dao
import cn.cdjs.entity.Product; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Repository; /** * ES data persistence layer * ElasticsearchRepository<Product,Long> * Product: ES document object of the specified operation * Long: The primary key type of the ES document object that specifies the operation */ @Repository public interface IProductDao extends ElasticsearchRepository<Product,Long> { }
6. Startup class
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class); } }
7. Test class
import cn.cdjs.dao.IProductDao; import cn.cdjs.entity.Product; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class ElasticSearchTest { @Autowired private ElasticsearchRestTemplate elasticsearchRestTemplate; @Autowired private IProductDao productDao; /** ======================================== Index related operations==== ====================================*/ @Test public void createIndex(){ // The system will automatically read the entity class configured by ES when the project is started. If the index is not used in the ES index library, it will be automatically created. } /* Delete index */ @Test public void deleteIndex(){ boolean flag = elasticsearchRestTemplate.deleteIndex(Product.class); System.out.println("Delete index results: " + flag); } /** ======================================== Document related operations==== ====================================*/ /* save data */ @Test public void save(){ Product product = new Product(); product.setId(2L); product.setCategory("mobile phone"); product.setImages("http://www.huawei.com"); product.setPrice(2999.0); product.setTitle("Huawei mobile phone"); // save data productDao.save(product); } /* update data */ @Test public void update(){ Product product = new Product(); product.setId(2L); product.setCategory("mobile phone"); product.setImages("http://www.xiaomi.com"); product.setPrice(6999.0); product.setTitle("Xiaomi mobile phone"); //Update data, if the ID is the same, call the save method to update, if the ID is different, add a new one productDao.save(product); } /* Query data based on ID */ @Test public void findById(){ Product product = productDao.findById(2L).get(); System.out.println("Query the data with ID 2: " + product); } /* Query all data under the index */ @Test public void findAll(){ Iterable<Product> products = productDao.findAll(); for (Product product:products) { System.out.println(product); } } /* delete data */ @Test public void delete(){ Product product = new Product(); product.setId(2L); productDao.delete(product); // or call productDao.deleteById(2L); } /* Add batches */ @Test public void saveAll(){ List<Product> list = new ArrayList<>(); for (int i = 3;i <= 10;i + + ){ Product product = new Product(); product.setId(Long.valueOf(i)); product.setCategory("mobile phone"); product.setImages("http://www.xiaomi.com"); product.setPrice(6999.0 + i); product.setTitle("[" + i + "]" + "Xiaomi phone"); list.add(product); } productDao.saveAll(list); } /* Paging query */ @Test public void findByPageable(){ //Set the sorting method (based on ID, descending order) Sort sort = Sort.by(Sort.Direction.DESC, "id"); // current page int currentPage = 0; //Number of items per page int pageSize = 5; //Set paging query conditions PageRequest pageRequest = PageRequest.of(currentPage, pageSize, sort); // Paging query Iterable<Product> products = productDao.findAll(pageRequest); for (Product product:products) { System.out.println(product); } } /** ======================================== Document search operation==== ====================================*/ /* term query */ @Test public void termQuery(){ TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("category", "mobile phone"); // Query the data whose category is "mobile phone" Iterable<Product> products = productDao.search(termQueryBuilder); for (Product product:products) { System.out.println(product); } } /* term query + paging */ @Test public void termQueryByPage(){ int currentPage = 0; int pageSize = 5; //Construct trem condition TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("category", "mobile phone"); //Construct sorting conditions Sort sort = Sort.by(Sort.Direction.DESC, "price"); // Build paging + sorting PageRequest pageRequest = PageRequest.of(currentPage, pageSize, sort); //Assemble query Page<Product> products = productDao.search(termQueryBuilder, pageRequest); for (Product product:products) { System.out.println(product); } } }
Note:QueryBuilders can be used to build different query conditions;
The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Cloud native entry-level skills treeHomepageOverview 16,891 people are learning the system