下面是一个使用Spring Boot 2.5连接Elasticsearch 7的示例程序,包括基本的功能,使用模板方法:
首先,确保你的项目中添加了以下依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
然后,创建一个Elasticsearch配置类,配置Elasticsearch连接信息:
java
@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()); } }
接下来,创建一个数据实体类,用于映射Elasticsearch中的文档:
java
@Document(indexName = "my_index", type = "my_type") public class MyEntity { @Id private String id; private String name; // getters and setters }
然后,创建一个数据访问接口,继承自ElasticsearchRepository
,用于操作Elasticsearch中的文档:
java
public interface MyEntityRepository extends ElasticsearchRepository<MyEntity, String> { List<MyEntity> findByName(String name); }
最后,创建一个Spring Boot应用程序类,编写一些简单的示例代码:
java
@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.properties
文件中配置Elasticsearch连接信息:
java
elasticsearch.host=localhost elasticsearch.port=9200
这样,就完成了一个使用Spring Boot连接Elasticsearch的简单示例程序。你可以根据自己的需求进一步扩展和定制。