您好,欢迎访问一九零五行业门户网

springboot中如何集成elasticsearch

1,引入依赖
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-data-elasticsearch</artifactid> </dependency>
2,编写实体映射类
@data@document(indexname = index, createindex = true)public class index { @id    private string id;    @field(type = fieldtype.text, analyzer = ik_max_word, searchanalyzer = ik_smart) private string content;}
3,编写访问接口(如果需要自动创建索引,该接口必须写,否则项目启动时不会自动检测并创建索引)
@repositorypublic interface indexrepository extends elasticsearchrepository<index, string> { page<index> findbycontent(string content, pageable page);}
4,测试,用了template,和repository两种方式测试
@springboottestpublic class estest { @autowired elasticsearchresttemplate estemplate; @autowired indexrepository indexrepository; @beforeeach public void init() { system.out.println(init); indexrepository.deleteall(); indexrepository.saveall(listutil.of( new index(1,美国留给伊拉克的是个烂摊子吗), new index(2,公安部:各地校车将享最高路权), new index(3,中韩渔警冲突调查:韩警平均每天扣1艘中国渔船), new index(4,中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首), new index(5,中国天眼向全球正式开放下月世界大赛将比拼fast脉冲星搜索) )); } @test void testrepositoryquery() { page<index> pagelist = indexrepository.findbycontent(中国, pagerequest.of(0, 10)); pagelist.getcontent().foreach(e -> { system.out.println(repositoryquery => +e); }); } @test void testtemplatequery() { boolquerybuilder querybuilder = querybuilders.boolquery() .must(querybuilders.simplequerystringquery(中国).field(content)); nativesearchquery query = new nativesearchquerybuilder() .withquery(querybuilder) .withpageable(pagerequest.of(0, 10)) .build(); searchhits<index> search = estemplate.search(query, index.class); if(search.hassearchhits()) { search.getsearchhits().foreach(e -> { system.out.println(templatequery => +e.getcontent()); }); } }}
init datatemplatequery => index(id=3, content=中韩渔警冲突调查:韩警平均每天扣1艘中国渔船)templatequery => index(id=4, content=中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首)templatequery => index(id=5, content=中国天眼向全球正式开放下月世界大赛将比拼fast脉冲星搜索)init datarepositoryquery => index(id=3, content=中韩渔警冲突调查:韩警平均每天扣1艘中国渔船)repositoryquery => index(id=4, content=中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首)repositoryquery => index(id=5, content=中国天眼向全球正式开放下月世界大赛将比拼fast脉冲星搜索)
5,可启动一个定时任务,定时ping,防止connection time out
    @scheduled(fixedrate = 15000) public void ping() { estemplate.execute(client -> client.ping(requestoptions.default)); }
以上就是springboot中如何集成elasticsearch的详细内容。
其它类似信息

推荐信息