Based on Sider-chatgpt3.5-write a demo program that uses springboot2.5 to connect elasticsearch7, including basic functions, using template method

The following is a sample program that uses Spring Boot 2.5 to connect to Elasticsearch 7, including basic functions, using the template method:

First, make sure you have the following dependencies added to your project:

 
 

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>

Then, create an Elasticsearch configuration class to configure Elasticsearch connection information:

 
 
@Configuration public class ElasticsearchConfig { @Value("${elasticsearch.host}") private String host; @Value("${elasticsearch.port}") private int port; @Bean public RestHighLevelClient elasticsearchClient() { RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, "http")); RestHighLevelClient client = new RestHighLevelClient(builder); return client; } @Bean public ElasticsearchOperations elasticsearchTemplate() { return new ElasticsearchRestTemplate(elasticsearchClient()); } }

Next, create a data entity class for mapping documents in Elasticsearch:

 
 
@Document(indexName = "my_index", type = "my_type") public class MyEntity { @Id private String id; private String name; // getters and setters }

Then, create a data access interface, inherited from ElasticsearchRepository, for manipulating documents in Elasticsearch:

 
 
public interface MyEntityRepository extends ElasticsearchRepository<MyEntity, String> { List<MyEntity> findByName(String name); }

Finally, create a Spring Boot application class and write some simple sample code:

 
 
@SpringBootApplication public class DemoApplication implements CommandLineRunner { @Autowired private MyEntityRepository myEntityRepository; public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Override public void run(String... args) throws Exception { // 创建一个文档 MyEntity entity = new MyEntity(); entity.setId("1"); entity.setName("John"); myEntityRepository.save(entity); // 根据名称查询文档 List<MyEntity> entities = myEntityRepository.findByName("John"); for (MyEntity e : entities) { System.out.println(e.getId() + ": " + e.getName()); } } }

application.propertiesConfigure the Elasticsearch connection information in the file :

 
 
elasticsearch.host=localhost elasticsearch.port=9200

In this way, a simple sample program that uses Spring Boot to connect to Elasticsearch is completed. You can further extend and customize it according to your needs.

Guess you like

Origin blog.csdn.net/jiao_zg/article/details/132587519