1.创建索引
1.2在项目启动后执行,先判断是否有这个索引,没有则创建
java//判断索引是否存在 BooleanResponse troubleShootLog = elasticsearchClient.indices().exists(e -> e.index(TroubleShootLog.INDEX));
java
private void createTroubleShootLogIndex() {
try {
elasticsearchClient.indices().create(c -> c
.index(TroubleShootLog.INDEX)//索引名称
.settings(s->s.numberOfShards(numberOfShards).numberOfReplicas(numberOfReplicas))
.mappings(mappings -> mappings //映射
.properties("docPoolId", p -> p
.long_(t -> t)
)
.properties("poolFileId", p -> p
.long_(t -> t)
)
.properties("type", p -> p
.long_(t -> t)
)
.properties("opt", p -> p
.integer(t -> t)
)
.properties("userId", p -> p
.long_(t -> t)
)
.properties("keyword", p -> p
.text(t -> t)
)
.properties("aircraftTypes", p -> p
.text(t -> t)
)
.properties("docType", p -> p
.text(t -> t)
)
.properties("cratedTime", p -> p
.date(t -> t.format("yyyy-MM-dd HH:mm:ss")) //
)
)
);
} catch (IOException e) {
log.error(e.getMessage(),e);
}
}
2.查询
java
//创建查询条件,查询text的内容
Query query = builder.bool(b -> b.must(m -> m.matchPhrasePrefix(h -> h.field("text").query(dto.getQ())))).build();
//执行查询
SearchResponse<PdfDoc> pdfDocOne = elasticsearchClient.search(s -> s
.index(PdfDoc.INDEX)//要查询的索引名称
.query(q -> q.bool(b -> b.must(query)))//查询条件
.highlight(setHighLight())//高亮字段
.from(dto.getPageNumber())//从第几页开始
.size(dto.getPageSize())//到第几页结束
.sort(so -> so.field(f -> f//排序
.field("_score").order(SortOrder.Desc)
.field("type").order(SortOrder.Desc)
.field("heat").order(SortOrder.Desc)
))
, PdfDoc.class
);
private Highlight setHighLight() {
Highlight highlight = Highlight.of(h -> h.preTags("<font color='red'>").postTags("</font>").fields("text", t -> t));
return highlight;
}