springboot版本2.7.3
elasticsearch版本7.17.4
版本兼容
https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#preface.requirements
搭建过程中踩到的坑有一个就是版本不兼容
环境搭建
使用docker搭建
docker pull elasticsearch:7.17.4
docker run -itd --name es7 \
-p 9200:9200 -p 9300:9300 \
-e "discovery.type=single-node" \
-e ES_JAVA_OPTS="-Xms64m -Xmx256m" \
elasticsearch:7.17.4
依赖
<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>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
application.yaml
spring:
elasticsearch:
uris:
- 127.0.0.1:9200
model
@Data
@Document(indexName = "book1")
public class Book {
@Id
private Integer id;
// @Field(type = FieldType.Text)
private String bookName;
// @Field(type = FieldType.Keyword)
private String authorName;
@Field(type = FieldType.Date, format = DateFormat.date_hour_minute_second)
private LocalDateTime recordTime;
}
repository
public interface BookRepository extends ElasticsearchRepository<Book, Integer> {
}
test
@SpringBootTest
class ElasticsearchApplicationTests {
@Autowired
BookRepository bookRepository;
//springboot自动配置ElasticsearchRestTemplate
@Autowired
ElasticsearchRestTemplate elasticsearchRestTemplate;
@Test
void saveTest() {
Book book = new Book();
book.setId(3);
book.setAuthorName("tcoding");
book.setBookName("hello spring boot");
book.setRecordTime(LocalDateTime.now());
bookRepository.save(book);
}
@Test
void getTest(){
Optional<Book> byId = bookRepository.findById(3);
byId.ifPresent(System.out::println);
}
@Test
void templateTet() {
System.out.println(elasticsearchRestTemplate.get("3", Book.class));
}
}
源码
https://github.com/googalAmbition/hello-spring-boot/tree/main/22-elasticsearch