elasticsearch 8.14.1 和 Spring Data elasticsearch 实例演示
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import java.io.Serializable;
// 定义Elasticsearch文档的实体类
@Document(indexName = "sampleindex")
public class SampleEntity implements Serializable {
@Id
private String id;
private String content;
// 标准的getter和setter方法
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
// 构造器
public SampleEntity(String id, String content) {
this.id = id;
this.content = content;
}
public SampleEntity() {
}
}
// 使用Spring Data Elasticsearch仓库进行操作
public interface SampleEntityRepository extends ElasticsearchRepository<SampleEntity, String> {
// 可以在这里定义更多的查询方法
}
// 示例:使用Spring Data Elasticsearch进行文档的创建和搜索
public class SampleElasticsearchApplication {
// 注入SampleEntityRepository
private final SampleEntityRepository repository;
public SampleElasticsearchApplication(SampleEntityRepository repository) {
this.repository = repository;
}
public void run() {
// 创建一个新的SampleEntity实例
SampleEntity sampleEntity = new SampleEntity("1", "Sample content");
// 将其保存到Elasticsearch
SampleEntity savedEntity = repository.save(sampleEntity);
// 使用Spring Data查询方法查询文档
Iterable<SampleEntity> entities = repository.findAll();
entities.forEach(entity -> System.out.println(entity.getContent()));
}
public static void main(String[] args) {
SpringApplication.run(SampleElasticsearchApplication.class, args);
}
}
这个代码示例展示了如何在Spring Data Elasticsearch中定义实体类、仓库接口,以及如何在应用程序中使用它们。它提供了一个简单的框架,开发者可以在此基础上根据自己的需求进行扩展和定制。
评论已关闭