首先是配置文件:但是方法都已经过期了,不必做其他配置
实体类:省略setget以及tostring方法,
其中@JestId为文档id,即Elasticsearch中的_id字段
public class Article {
@JestId
private Integer id;
private String author;
private String title;
private String content;
}
@Document注解标明实体是elasticsearch种的Document,其属性可以标明属于的索引和类型----对应数据库中的数据库名和表名,其中type不预先创建也可以,没预先创建的它会自动创建一个与实体相匹配的type
但是在ES高版本中,type类型弃用了
@Document(indexName = "atguigu"/*,type = "book"*/)
public class Book {
private Integer id;
private String bookName;
private String author;
}
Springboot整合Jest操作ES:
在高版本中,JestClient好像没有自动注入了,要手动注入:
可以写在配置类里用@Autowired注入,我就直接写在测试类中:
public JestClient getJestCline(){
JestClientFactory factory = new JestClientFactory();
factory.setHttpClientConfig(new HttpClientConfig
.Builder("http://192.168.1.6:9200")
.multiThreaded(true)
.build());
return factory.getObject();
}
ES中索引(保存)一个文档并构建索引功能:
@Test
public void contextLoads() {
JestClient jestClient = getJestCline();
//1、给Es中索引(保存)一个文档
Article article = new Article();
article.setId(1);
article.setTitle("好消息哟");
article.setAuthor("zhangsan");
article.setContent("hello world");
//构建一个索引功能
Index index = new Index.Builder(article).index("atguigu").type("news").build();
try {
//执行
jestClient.execute(index);
} catch (IOException e) {
e.printStackTrace();
}
}
测试搜索
@Test
public void search(){
//查询表达式
String json="{\n" +
"\t\"query\" : {\n" +
"\t\t\"match\" : {\n" +
"\t\t\t\"content\" : \"hello\"\n" +
"\t\t}\n" +
"\t}\n" +
"}";
//构建搜索功能
Search search = new Search.Builder(json).addIndex("atguigu").addType("news").build();
//执行
JestClient jestClient = getJestCline();
try {
SearchResult result = jestClient.execute(search);
System.out.println(result.getJsonString());
} catch (IOException e) {
e.printStackTrace();
}
}
整合SpringDataElasticsearch:
高版本中废弃了很多方法,官方推荐使用 RestHighLevelClient
@Configuration
public class ElasticsearchConfig {
@Bean
RestHighLevelClient elasticsearchClient() {
ClientConfiguration configuration = ClientConfiguration.builder()
.connectedTo("192.168.1.6:9200")
//.withConnectTimeout(Duration.ofSeconds(5))
//.withSocketTimeout(Duration.ofSeconds(3))
//.useSsl()
//.withDefaultHeaders(defaultHeaders)
//.withBasicAuth(username, password)
// ... other options
.build();
RestHighLevelClient client = RestClients.create(configuration).rest();
return client;
}
}
自定义的Repository:
public interface BookRepository extends ElasticsearchRepository<Book,Integer> {
}
保存文档:
@Test
public void test02(){
Book book=new Book();
book.setId(1);
book.setBookName("金瓶梅");
book.setAuthor("兰陵笑笑生");
bookRepository.save(book);*/
}
在ES中按照书名来查找,只需要写方法名,不用写实现
public interface BookRepository extends ElasticsearchRepository<Book,Integer> {
public List<Book> findByBookNameLike(String bookName);
}
测试模糊查询:
@Test
public void test02(){
/*Book book=new Book();
book.setId(1);
book.setBookName("金瓶梅");
book.setAuthor("兰陵笑笑生");
bookRepository.save(book);*/
for (Book book : bookRepository.findByBookNameLike("梅")) {
System.out.println(book);
}
;
}
在控制台打印出金瓶梅