直接说操作吧,只需要勾选springboot的web模块:
然后在pom文件中添加下面的依赖:
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>6.3.1</version>
</dependency>
博主想按照书上写的,在application.properties中指定一下elasticsearch服务部的ip和端口,结果发现这种方法已经过时了:
并且,jestClient没有自动注入进来,博主猜想大概是springboot2.2版本以后以及没有自动给容器注入jest了。
到这里,很多小伙伴决定放弃jest的学习,毕竟这个方法都过时了。但博主依旧发挥共产党的坚持不懈精神,springboot不自动注入,那我就自己注入,将下面的bean 纳入Ioc容器。该bean依旧解决了指定elastic服务地址的任务。所以再无需任何配置, 直接使用。
@Configuration
public class MyConfig {
@Bean
public JestClient jestClient(){
JestClientFactory factory = new JestClientFactory();
factory.setHttpClientConfig(new HttpClientConfig
.Builder("http://192.168.31.53:9200")
.multiThreaded(true)
.build());
return factory.getObject();
}
}
使用实例:
@SpringBootTest
class BootelasticsearchApplicationTests {
@Autowired
JestClient jestClient;
//放数据
@Test
void contextLoads() {
Article article = new Article();
article.setId(1);
article.setTitle("good night");
article.setAuthor("lzl");
article.setContent("hello world");
Index index = new Index.Builder(article).index("lzl").type("news").build();
try {
jestClient.execute(index);
} catch (IOException e) {
e.printStackTrace();
}
}
//查数据
@Test
public void search(){
String json = "{\n" +
" \"query\" : {\n" +
" \t\t\"match\" : {\n" +
" \t\t\t\"content\" : \"hello\"\n" +
" \t\t}\n" +
" }\n" +
"}";
//构建搜索功能
Search search = new Search.Builder(json).addIndex("lzl").addType("news").build();
try {
SearchResult execute = jestClient.execute(search);
System.out.println(execute.getJsonString());
} catch (IOException e) {
e.printStackTrace();
}
}
}