1、jest
使用Maven依赖
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>5.3.3</version>
</dependency>
测试
使用注解
@Autowired
JestClient jestClient;
//添加数据
@Test
void contextLoads() throws IOException {
User user=new User();
user.setId(1);
user.setGenter(1);
user.setUserName("lhs");
user.setAddress("nanchang");
Index build = new Index.Builder(user).index("nanchang").type("student").build();
jestClient.execute(build);
}
//进行搜索,搜索匹配到last_name为Smith的数据
@Test
void testQuery() throws IOException {
String query="{\n" +
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"last_name\" : \"Smith\"\n" +
" }\n" +
" }\n" +
"}";
Search build = new Search.Builder(query).addIndex("nanchang").addType("student").build();
SearchResult execute = jestClient.execute(build);
System.out.println(execute);
}
2、使用spring-boot-starter-data-elasticsearch实现
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
实现接口
public interface BookRepository extends ElasticsearchRepository {
public List<Book> findByBookNameLike(String bookName);
}
@Autowired
BookRepository bookRepository;
//添加数据
@Test
void addElasticSearch(){
Book book=new Book();
/* book.setBookId(1);
book.setBookName("三国演义");
book.setBookNo(10);*/
bookRepository.index(book);
}
//查找
@Test
void searchBook(){
List<Book> listBook = bookRepository.findByBookNameLike("三");
for(Book book1:listBook){
System.out.println(book1);
}
}