ElasticSearch 的检索没有Solr那么多类别,ElasicSearch默认是模糊查询,通过使用余弦相似度量算法来判断keyword和检索值的相似度,然后取出相似度最高的数据作为返回。
//检索主体函数 public JSONArray Query(String keyword) { //单字段查询 //MatchQueryBuilder query = QueryBuilders.matchQuery("poi_title", "xxxx大学"); //多字段查询字段 MultiMatchQueryBuilder query = QueryBuilders.multiMatchQuery(keyword, "poi_address","poi_title","poi_tags"); //高亮 HighlightBuilder highlight = new HighlightBuilder(); highlight.preTags("<span class = ‘highlight‘>") .postTags("</span>") .field("poi_title") .field("poi_address") .field("poi_tags"); //检索设置 SearchResponse response = client.prepareSearch("pois") .setTypes("cxyword") .setQuery(query) .highlighter(highlight) .setFrom(0) .setSize(5) //从0开始,默认推荐5个 .execute() .actionGet(); //执行检索 SearchHits hits = response.getHits(); //以json数组存储搜索结果 JSONArray jsonArray = new JSONArray(); JSONObject jsonObject = null; System.out.println("共搜到:"+hits.getTotalHits()+"条结果"); for (SearchHit hit : hits) { jsonObject = new JSONObject(); //首先判断该字段是否存在高亮,存在则拉取高亮,不存在则拉取整个字段 jsonObject.put("poi_title", hit.getHighlightFields().get("poi_title") != null ? getFraStr(hit.getHighlightFields().get("poi_title").getFragments()): hit.getSource().get("poi_title")); jsonObject.put("poi_address", hit.getHighlightFields().get("poi_address") != null ? getFraStr(hit.getHighlightFields().get("poi_address").getFragments()): hit.getSource().get("poi_address")); jsonObject.put("poi_tags", hit.getHighlightFields().get("poi_tags") != null ? getFraStr(hit.getHighlightFields().get("poi_tags").getFragments()): hit.getSource().get("poi_tags")); jsonObject.put("poi_lat", hit.getSource().get("poi_lat")); jsonObject.put("poi_lng", hit.getSource().get("poi_lng")); jsonObject.put("poi_photel", hit.getSource().get("poi_photel")); jsonObject.put("id", hit.getId()); jsonArray.add(jsonObject); } return jsonArray; }
时间: 2024-10-10 23:36:16