- 引入版本依赖
<!--spring-boot-starter-parent的版本号[2.2.0.RELEASE]要和[Hoxton.RELEASE]的版本对应 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
</parent>
- 加入elasticsearch模块(springboot已经整合好的,lombok模块不是必须的)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
- 编写实体
package com.satuo20.entity;
import lombok.*;
import lombok.experimental.Accessors;
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;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Document(indexName = "book",type = "_doc")
public class Book {
@Id
private String id;
@Field(type = FieldType.Text,analyzer = "ik_max_word")
private String name;
@Field(type = FieldType.Text,analyzer = "ik_max_word")
private String content;
@Field(type = FieldType.Keyword)
private String author;
@Field(type = FieldType.Double)
private Double price;
@Field(type = FieldType.Date)
private Date pubDate;
}
- 编写repository
package com.satuo20.repository;
import com.satuo20.entity.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;
import java.util.Optional;
public interface BookRepository extends ElasticsearchRepository<Book,String> {
Optional<Book> findByName(String name);
/**
* 用法和jpa类似
* @param name
* @param content
* @return
*/
List<Book> findByNameAndContent(String name,String content);
}
- 调用
package com.satuo20;
import com.satuo20.entity.Book;
import com.satuo20.repository.BookRepository;
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.test.context.junit4.SpringRunner;
import java.util.Date;
import java.util.Optional;
@SpringBootTest(classes = ElasticApp.class)
@RunWith(SpringRunner.class)
public class AppTest {
@Autowired
private BookRepository bookRepository;
@Test
public void testSave() {
Book book = new Book("998","saas","this is content","zhangsan",200d,new Date());
bookRepository.save(book);
}
@Test
public void testFindByName() {
Optional<Book> book = bookRepository.findByName("saas");
System.err.println(book.get());
}
}
注意:本文归作者所有,未经作者允许,不得转载