1.添加依赖
<!--elasticsearch依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2.yml中增加es配置
spring
elasticsearch:
rest:
uris: http://127.0.0.1:9200
3.索引实体类
@Data
@FieldNameConstants
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "index_search")
public class IndexSearch {
@Id
private long id;
@ApiModelProperty(value = "名称")
@Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
private String name;
@ApiModelProperty(value = "别名")
@Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
private String displayName;
@ApiModelProperty(value = "分类 1类型 2物质 3省 4市")
@Field(type = FieldType.Integer)
private Integer category;
@ApiModelProperty(value = "时间")
@Field(type = FieldType.Date, format = DateFormat.basic_date, pattern = "yyyy-MM-dd")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date controlTime;
@ApiModelProperty(value = "包含隶属")
@Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
private String contain;
@ApiModelProperty(value = "主要省")
@Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
private String mainProvince;
@ApiModelProperty(value = "次要省")
@Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
private String secondaryProvince;
@ApiModelProperty(value = "主要市")
@Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
private String mainCity;
@ApiModelProperty(value = "次要市")
@Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
private String secondaryCity;
@ApiModelProperty(value = "其他省")
@Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
private String otherProvince;
@ApiModelProperty(value = "其他市")
@Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
private String otherCity;
/*
定义关键词索引 要完成补全搜索,必须要用到特殊的数据类型completion,
要汉字拼音都能补全,必须要使用自定义的ik+pinyin分词器
maxInputLength:设置单个输入的长度,默认为50 UTF-16 代码点*/
@CompletionField(analyzer = "ik_max_word", searchAnalyzer = "keyword", maxInputLength = 100)
private Completion completion;
}
4.实现Repository
public interface IndexSearchRepository extends ElasticsearchRepository<IndexSearch, Long> {
@Highlight(
fields = {
@HighlightField(name = "name"),
@HighlightField(name = "displayName"),
},
parameters = @HighlightParameters(preTags = "<strong>",
postTags = "</strong>", fragmentSize = 500,numberOfFragments= 3))
SearchPage<IndexSearch> findByNameOrDisplayName(String name,String displayName, Pageable pageable);
}
5.控制器具体实现
分页查询,高亮查询
@Autowired
private SubstanceSearchRepository repository;
//使用es API进行分页高亮查询
@GetMapping("/listSearch")
public RestResult<ListPageResult<IndexSearch>> getPageData(@RequestParam String name,
@RequestParam(defaultValue = "0") Integer pageNumber,
@RequestParam(defaultValue = "10") Integer pageSize) {
SearchPage<SubstanceSearch> pageData = repository.findByNameOrDisplayName(name, name,PageRequest.of(pageNumber, pageSize));
try {
// 得到查询结果返回的内容
List<SearchHit<IndexSearch>> searchHits = pageData.getContent();
// 设置一个需要返回的实体类集合
List<IndexSearch> discussPosts = new ArrayList<>();
// 遍历返回的内容进行处理
for (SearchHit<IndexSearch> searchHit : searchHits) {
// 高亮的内容
Map<String, List<String>> highLightFields = searchHit.getHighlightFields();
// 将高亮的内容填充到content中
searchHit.getContent().setName(highLightFields.get("name") == null ? searchHit.getContent().getName() : highLightFields.get("name").get(0));
searchHit.getContent().setDisplayName(highLightFields.get("displayName") == null ? searchHit.getContent().getDisplayName() : highLightFields.get("displayName").get(0));
// 放到实体类中
discussPosts.add(searchHit.getContent());
}
return RestResultHelper.success(new ListPageResult<IndexSearch>(pageData.getSize(), pageData.getNumber(), pageData.getTotalPages(), pageData.getTotalElements(), discussPosts));
} catch (Exception e) {
e.printStackTrace();
return RestResultHelper.error();
}
}
自动补全
@Autowired
private ElasticsearchRestTemplate restTemplate;
/**
* 自动补全方法
**/
@GetMapping("/suggest")
public RestResult<List<String>> suggest(String prefix) {
List<String> results = new ArrayList<>();
CompletionSuggestionBuilder completionSuggestionBuilder = new CompletionSuggestionBuilder(IndexSearch.Fields.completion)
.prefix(prefix)
.skipDuplicates(true).size(10);
SuggestBuilder suggestBuilder = new SuggestBuilder()
.addSuggestion("name_suggest", completionSuggestionBuilder);
SearchResponse response = restTemplate.suggest(suggestBuilder, IndexCoordinates.of("index_search"));
Suggest suggest = response.getSuggest();
Suggest.Suggestion suggestion = suggest.getSuggestion("name_suggest");
List<CompletionSuggestion.Entry> entries = suggestion.getEntries();
entries.forEach(entry -> {
List<CompletionSuggestion.Entry.Option> options = entry.getOptions();
options.forEach(option -> {
results.add(option.getText().toString());
});
});
return RestResultHelper.success(results);
}
添加文档数据文章来源:https://www.toymoban.com/news/detail-552279.html
//添加数据
@Autowired
private SubstanceSearchRepository repository;
@GetMapping("/insert")
public void addData() throws Exception {
List<IndexSearch> orderDocs = new ArrayList<>();
for (int i = 0; i < 15; i++) {
String title = "类型";
suggestList = new ArrayList<>();
title += i;
suggestList.add(title); //可以把多个内容作为suggest的数据源
suggestList.add("别名" + i);
Completion suggest = new Completion(suggestList.toArray(new String[suggestList.size()]));
IndexSearch orderDoc = new IndexSearch(i, title, title, 1, new Date(), "隶属", "主要省", "次要省", "主要市", "次要市", "其他省", "其他市",suggest);
orderDocs.add(orderDoc);
}
repository.saveAll(orderDocs);
}
文章来源地址https://www.toymoban.com/news/detail-552279.html
到了这里,关于springboot与es集成操作-基础篇的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!