springboot整合ES的依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> spring.data.elasticsearch.cluster-name=my-application spring.data.elasticsearch.cluster-nodes=localhost:9300 spring.data.elasticsearch.repositories.enabled=true1.使用elasticsearchRepository
这种方式简单方便,以操作repository的方式操作ES 不了解ES的开发者也可以简单使用
创建实体类,
指定index(数据库) type(数据库中的表) 分片和副本不是必须的
@Document(indexName = "book",type = "book", shards = 1,replicas = 0, refreshInterval = "-1") public class Book { //注意 实现的实体类必须指定id属性 不然会报异常 private Integer id; private String bookName; private String author; private String publish; private Integer price; // setXXX()和getXXX() @Override public String toString() { return "Book{" + "id=" + id + ", bookName='" + bookName + '\'' + ", author='" + author + '\'' + ", publish='" + publish + '\'' + ", price=" + price + '}'; } }创建dao层
只需要继承ElasticSearchRepository<Book,String>的接口 不需要自己去实现接口
接口上 可以不使用任何注解(如:@Repository)
public interface BookRepository extends ElasticsearchRepository<Book, String> { List<Book> findByPrice(Integer price); }测试类。。。
@RunWith(SpringRunner.class) @SpringBootTest public class ElasticsearchApplicationTests { @Autowired BookRepository bookRepository; @Test public void test1(){ Book book=new Book(); book.setAuthor("张三"); book.setBookName("javv从入门到放弃"); book.setPrice(24); book.setPublish("出版社"); bookRepository.save(book); Iterable<Book> all = bookRepository.findAll(); Iterator<Book> iterator = all.iterator(); while(iterator.hasNext()) { Book next = iterator.next(); System.out.println(next); } } }2.使用elasticsearchTemplate
直接注入elasticsearchTemplate
@Autowired ElasticsearchTemplate elasticsearchTemplate; @Test public void test2(){ Client client = elasticsearchTemplate.getClient(); GetResponse response = client.prepareGet("index", "type", "id").get(); System.out.println(response.getSource()); }以上只是简单的使用 elasticsearchTemplate方式的 如果想详细了解client的使用 --> client的常用操作API