今天就跟大家聊聊有關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,編寫訪問接口(如果需要自動創建索引,該接口必須寫,否則項目啟動時不會自動檢測并創建索引)
其中repository具體方法命名規則參考官網:https://docs.spring.io/spring-data/elasticsearch/docs/4.1.7/reference/html/#elasticsearch.query-methods
@Repository
public interface IndexRepository extends ElasticsearchRepository<Index, String> {
Page<Index> findByContent(String content, Pageable page);
}4,測試,用了template,和repository兩種方式測試
@SpringBootTest
public 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 data templateQuery => Index(id=3, content=中韓漁警沖突調查:韓警平均每天扣1艘中國漁船) templateQuery => Index(id=4, content=中國駐洛杉磯領事館遭亞裔男子槍擊 嫌犯已自首) templateQuery => Index(id=5, content=中國天眼向全球正式開放下月世界大賽將比拼FAST脈沖星搜索) init data repositoryQuery => 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有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。