0


使用Postman创建ES索引

put请求添加索引

http://192.159.138.73:9200/app_info_article

image.png

请求内容

 { "mappings":{ "properties":{ "id":{ "type":"long" }, "publishTime":{ "type":"date" }, "layout":{ "type":"integer" }, "images":{ "type":"keyword", "index": false }, "staticUrl":{ "type":"keyword", "index": false }, "authorId": { "type": "long" }, "authorName": { "type": "text" }, "title":{ "type":"text", "analyzer":"ik_smart" }, "content":{ "type":"text", "analyzer":"ik_smart" } } } } 

image.png

其他操作

GET请求查询映射:

http://192:168:200:129:9200/app_info_article

DELETE请求删除索引及映射:

http://192:168:200:129:9200/app_info_article

GET请求查询所有文档:

http://192:168:200:129:9200/app_info_article/_search

SpringBoot 集成ES

导入依赖

 <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.12.1</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>7.12.1</version> </dependency> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.12.1</version> </dependency> 

导入数据到es


@SpringBootTest @RunWith(SpringRunner.class) public class ApArticleTest {

@Autowired
private ApArticleMapper apArticleMapper;

@Autowired
private RestHighLevelClient restHighLevelClient;

/**

  • 注意:数据量的导入,如果数据量过大,需要分页导入
  • @throws Exception

*/
@Test
public void init() throws Exception {

//1.查询所有符合条件的文章数据
List<SearchArticleVo> searchArticleVos = apArticleMapper.loadArticleList();

//2.批量导入到es索引库

BulkRequest bulkRequest = new BulkRequest("app_info_article");

for (SearchArticleVo searchArticleVo : searchArticleVos) {

    IndexRequest indexRequest = new IndexRequest().id(searchArticleVo.getId().toString())
            .source(JSON.toJSONString(searchArticleVo), XContentType.JSON);

    //批量添加数据
    bulkRequest.add(indexRequest);

}
restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

}


} ```

### 查询示例

``` @Service @Slf4j public class ArticleSearchServiceImpl implements ArticleSearchService {

@Autowired
private RestHighLevelClient restHighLevelClient;

@Autowired
private ApUserSearchService apUserSearchService;

/**

  • es文章分页检索
  • @param dto
  • @return

*/
@Override
public ResponseResult search(UserSearchDto dto) throws IOException {

//1.检查参数
if(dto == null || StringUtils.isBlank(dto.getSearchWords())){
    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}

ApUser user = AppThreadLocalUtil.getUser();

//异步调用 保存搜索记录
if(user != null && dto.getFromIndex() == 0){
    apUserSearchService.insert(dto.getSearchWords(), user.getId());
}

//2.设置查询条件
SearchRequest searchRequest = new SearchRequest("app_info_article");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

//布尔查询
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

//关键字的分词之后查询
QueryStringQueryBuilder queryStringQueryBuilder =
        QueryBuilders
        .queryStringQuery(dto.getSearchWords())
        .field("title")
        .field("content")
        .defaultOperator(Operator.OR);
boolQueryBuilder.must(queryStringQueryBuilder);

//查询小于mindate的数据
RangeQueryBuilder rangeQueryBuilder =
        QueryBuilders
        .rangeQuery("publishTime")
        .lt(dto.getMinBehotTime().getTime());
boolQueryBuilder.filter(rangeQueryBuilder);

//分页查询
searchSourceBuilder.from(0);
searchSourceBuilder.size(dto.getPageSize());

//按照发布时间倒序查询
searchSourceBuilder.sort("publishTime", SortOrder.DESC);

//设置高亮  title
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("title");
highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
highlightBuilder.postTags("</font>");
searchSourceBuilder.highlighter(highlightBuilder);

searchSourceBuilder.query(boolQueryBuilder);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

//3.结果封装返回

List<Map> list = new ArrayList<>();

SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit hit : hits) {
    String json = hit.getSourceAsString();
    Map map = JSON.parseObject(json, Map.class);
    //处理高亮
    if(hit.getHighlightFields() != null && hit.getHighlightFields().size() > 0){
        Text[] titles = hit.getHighlightFields().get("title").getFragments();
        String title = StringUtils.join(titles);
        //高亮标题
        map.put("h_title",title);
    }else {
        //原始标题
        map.put("h_title",map.get("title"));
    }
    list.add(map);
}

return ResponseResult.okResult(list);

}


} ```

### 相关文章

ES 基本操作:

https://juejin.cn/post/7243828605045047357
```


本文转载自: https://blog.csdn.net/weixin_45924250/article/details/131827853
版权归原作者 飞宇千虹 所有, 如有侵权,请联系我们删除。

“使用Postman创建ES索引”的评论:

还没有评论