elasticsearch之搜索

上篇写了es的简单概念以及版本集成sb方面,这篇将操作客户端进行查询

开启es支持

//开启es支持,
@EnableElasticsearchRepositories
public class Application implements CommandLineRunner {
	.....
}

写接口

1.这里以查询用户信息为例

1.1 添加文档,索引和类型实体

@Mapping(mappingPath = "/user")
@Data
@Document(indexName = "user",type = "user")
public class User {


    @Field
    private Integer id;

    @Field
    private String name;

    @Field
    private Integer age;

}

1.2 写接口,创建索引,并设置文档的字段类型(映射类型即上一步的字段值)

public class EsController {
     // 注入es模板
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    //添加索引接口 创建索引
    @RequestMapping("/es/addIndex/{index}")
    public Object addIndex(@PathVariable String index){

        boolean index1 = elasticsearchTemplate.createIndex(index);
        System.out.println(index1);
        return elasticsearchTemplate.createIndex(User.class);
    }

1.3 初始化数据

@RequestMapping("/es/putData")
    public void putData(){
        //这里利用es的批量命令来写入数据
        List<User> users = new ArrayList<>();
        BulkRequest bulkRequest = new BulkRequest();
        for (int i = 0; i < 1000; i++) {
            User user = new User();
            user.setId(i);
            user.setAge(new Random().nextInt(30));
            user.setName("test" + i);
            IndexRequest request = new IndexRequest();
            request.index("user")
                    .source(BeanUtil.beanToMap(user))
                    .id(i+"").type("_doc");
             bulkRequest.add(request);
        }
        elasticsearchTemplate.getClient().bulk(bulkRequest, new ActionListener<BulkResponse>() {
            @Override
            public void onResponse(BulkResponse bulkItemResponses) {
                System.out.println(bulkItemResponses);
            }

            @Override
            public void onFailure(Exception e) {
                System.out.println(e);
            }
        });
    }

1.4 查询
1.4.1 这里利用上一篇的bool查询来进行展开

@RequestMapping("/es/query")
    public Object query(User user){
	//构建一个查询 匹配姓名
        MatchQueryBuilder queryBuilder = QueryBuilders
                .matchQuery("name", user.getName()); 
        //高亮姓名的字段
        HighlightBuilder.Field highlightField
                = new HighlightBuilder.Field("name")
                .preTags("<span color='red'>")
                .postTags("</span>");
         //并且根据权重分数排序
        ScoreSortBuilder scoreSortBuilder = SortBuilders.scoreSort();
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //多个索引搜 用withIndices
        SearchQuery query = nativeSearchQueryBuilder.withIndices("user").withTypes("_doc") .withSort(scoreSortBuilder).withHighlightFields(highlightField)
////这里构造一个bool类型的查询,并加入了match子句的匹配
.withQuery(QueryBuilders.boolQuery().should(queryBuilder)).build();
        AggregatedPage users = elasticsearchTemplate.queryForPage(query, User.class, new SearchResultMapper() {
            @Override
            public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
//匹配完成之后分页 填充高亮字段的值 并返回给用户
      SearchHits hits = response.getHits();
      SearchHit[] hitArr = hits.getHits();
      List<Map> list = new ArrayList<>();
      for (SearchHit hit : hitArr) {
         Map<String, HighlightField> highlightFields = hit.getHighlightFields();
         HighlightField field = highlightFields.get("name");
         Text[] fragments = field.fragments();
         StringBuilder nameStr = new StringBuilder();
         ///这里返回高亮字段
         for (Text fragment : fragments) {
             nameStr.append(fragment.string());
        }
        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
       float score = hit.getScore();
       sourceAsMap.put("nameLineHigh", nameStr.toString());
       sourceAsMap.put("score", score);
       list.add(sourceAsMap);
     }
      return new AggregatedPageImpl(list, pageable, hits.totalHits,hits.getMaxScore());
      }
  });
   return users;
}

image.png

# 搜索  

评论

公众号:mumuser

企鹅群:932154986

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×