Node接入 node client(客户端相当于一个node接入)

Transport接入 transport client(5之前多用这种方式,基于二进制设计效率比较高)

Http接入 rest client(基于http通信,做到了不受语言限制,不受框架限制,5之后推介这种方式,7之后es会废弃Transport方式)


#申明es服务地址
elasticsearch.ip1=192.168.1.67:9300 //记得是9200端口,看es配置,之前这里搞错es通信连接不上很难判断错误
/*
ES连接不上判断方式
1.端口配置
2.是否网络IO不足,超时时间太短
3.hostname是否配置对,第一次最好用ip
*/
public class ElasticsearchRestClient2 {
    @Value("${elasticsearch.ip1}")
    String ipAddress;
    @Bean(name="highLevelClient")

    public RestHighLevelClient highLevelClient()
    {
        String [] address = ipAddress.split(":");
        String ip = address[0];
        int port = Integer.valueOf(address[1]);
        HttpHost httpHost = new HttpHost(ip,port,"http");
        RestClientBuilder builder = RestClient.builder(
                new HttpHost("192.168.1.67", 9200, "http")); builder.setRequestConfigCallback(
            new RestClientBuilder.RequestConfigCallback() {
                @Override
                public RequestConfig.Builder customizeRequestConfig(
                        RequestConfig.Builder requestConfigBuilder) {
                    return requestConfigBuilder.setConnectionRequestTimeout(-1);
                }
            });
        return new RestHighLevelClient(builder);
    }

//使用es查询的方法,等有空独立做个工具类,不过各个版本不同应该有区别我用的是7.6.1
@Override
public Map<String, Object> searchES(BigDecimal longitude, BigDecimal latitude, String keyword, Integer orderby, Integer categoryId, String tags) throws IOException {
    Map<String,Object> result = new HashMap<String,Object>();
    SearchRequest searchRequest = new SearchRequest("shop");
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

    List<Integer> shopIdsList = new ArrayList<>();
    sourceBuilder.query(QueryBuilders.matchQuery("name",keyword));
    sourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));
    searchRequest.source(sourceBuilder);

    SearchResponse searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
    SearchHit[] hits  = searchResponse.getHits().getHits();
    for(SearchHit hit : hits)
    {
        shopIdsList.add(new Integer(hit.getSourceAsMap().get("id").toString()));
    }
    List<ShopModel> shopModelList = shopIdsList.stream().map(
            id -> {
                return get(id);
            }
    ).collect(Collectors.toList());
    result.put("shop",shopModelList);
    return result;
}

 



//但是对于过于复杂的kibanna查询,用java es 高阶API去做查询显然十分麻烦,可以通过es的高阶调用低阶API去传递JSON字符串做类似KIBANNA查询


  @Override
    public List<ShopModel> search(BigDecimal longitude, BigDecimal latitude, String keyword,Integer orderby,Integer categoryId,String tags) {
        List<ShopModel> shopModelList = shopModelMapper.search(longitude,latitude,keyword,orderby,categoryId,tags);
        shopModelList.forEach(
                shopModel -> {
                    shopModel.setSellerModel(sellerService.get(shopModel.getSellerId()));
                    shopModel.setCategoryModel(categoryService.get(shopModel.getCategoryId()));
                }
        );
        return shopModelList;
    }

    @Override
    public Map<String, Object> searchES(BigDecimal longitude, BigDecimal latitude, String keyword, Integer orderby, Integer categoryId, String tags) throws IOException {
        Map<String,Object> result = new HashMap<String,Object>();
//        SearchRequest searchRequest = new SearchRequest("shop");
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//
//        List<Integer> shopIdsList = new ArrayList<>();
//        sourceBuilder.query(QueryBuilders.matchQuery("name",keyword));
//        sourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));
//        searchRequest.source(sourceBuilder);
//
//        SearchResponse searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//        SearchHit[] hits  = searchResponse.getHits().getHits();
//        for(SearchHit hit : hits)
//        {
//            shopIdsList.add(new Integer(hit.getSourceAsMap().get("id").toString()));
//        }
        Request request = new Request("GET","/shop/_search");
        String reqJson =
                "{\n" +
                "    \"_source\": \"*\", \n" +
                "    \"script_fields\": {\n" +
                "      \"distance\":{\n" +
                "        \"script\":{\n" +
                "          \"source\":\"haversin(lat,lon,doc['location'].lat,doc['location'].lon)\",\n" +
                "          \"lang\":\"expression\",\n" +
                "          \"params\":{\"lat\":" + latitude.toString() + ",\"lon\":" + longitude.toString() + "}\n" +
                "        \n" +
                "      }\n" +
                "    }\n" +
                "  },\n" +
                "  \"query\": {\n" +
                "    \"function_score\": {\n" +
                "      \"query\": {\n" +
                "        \"bool\": {\n" +
                "        \"must\": [\n" +
                "        {\"match\": {\"name\": {\"query\": \"" + keyword +  "\",\"boost\": 0.1}}},\n" +
                "        {\"term\": {\"seller_disabled_flag\": 0}}\n" +
                "      ]}},\n" +
                "      \"functions\": [\n" +
                "        {\n" +
                "          \"gauss\": {\n" +
                "            \"location\": {\n" +
                "              \"origin\": \"" + latitude.toString() + "," + longitude.toString() +  "\",\n" +
                "              \"scale\": \"100km\",\n" +
                "              \"offset\": \"0km\",\n" +
                "              \"decay\": 0.5\n" +
                "            }\n" +
                "          },\n" +
                "          \"weight\": 9\n" +
                "        },\n" +
                "        {\n" +
                "          \"field_value_factor\": {\n" +
                "            \"field\": \"remark_score\"\n" +
                "          },\n" +
                "          \"weight\": 0.2\n" +
                "        },\n" +
                "        {\n" +
                "          \"field_value_factor\": {\n" +
                "            \"field\": \"seller_remark_score\"\n" +
                "          },\n" +
                "          \"weight\": 0.1\n" +
                "        }\n" +
                "      ],\n" +
                "      \"score_mode\": \"sum\",\n" +
                "      \"boost_mode\": \"replace\"\n" +
                "    }\n" +
                "  }\n" +
                "  , \"sort\": [\n" +
                "    {\n" +
                "      \"_score\": {\n" +
                "        \"order\": \"desc\"\n" +
                "      }\n" +
                "    }\n" +
                "  ]\n" +
                "  \n" +
                "  \n" +
                "}";
        System.out.println(reqJson);
        System.out.println("===========================================================");
request.setJsonEntity(reqJson);
Response response = highLevelClient.getLowLevelClient().performRequest(request);
        String responseStr = EntityUtils.toString(response.getEntity());
        System.out.println(responseStr);
        JSONObject jsonObject = JSONObject.parseObject(responseStr);
        JSONArray jsonArray = jsonObject.getJSONObject("hits").getJSONArray("hits");
        List<ShopModel> shopModelList = new ArrayList<>();
        for(int i = 0;i<jsonArray.size();i++)
        {
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            Integer id = new Integer(jsonObj.get("_id").toString());
            //jsonObj.getJSONObject("fields").getJSONArray("distance").get(0);
            BigDecimal distance = new BigDecimal(jsonObj.getJSONObject("fields")
            .getJSONArray("distance").get(0).toString());
            ShopModel shopModel = get(id);
            //shopModel.setDistance(distance.setScale(0,BigDecimal.ROUND_CEILING).intValue() * 1000);
            shopModel.setDistance(distance.multiply(new BigDecimal(1000).setScale(0,BigDecimal.ROUND_CEILING)).intValue());
            shopModelList.add(shopModel);

        }
//        List<ShopModel> shopModelList = shopIdsList.stream().map(
//                id -> {
//                    return get(id);
//                }
//        ).collect(Collectors.toList());
        result.put("shop",shopModelList);
        return result;
    }