• es客户端查询服务器的三种模式


    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 =
                    "{
    " +
                    "    "_source": "*", 
    " +
                    "    "script_fields": {
    " +
                    "      "distance":{
    " +
                    "        "script":{
    " +
                    "          "source":"haversin(lat,lon,doc['location'].lat,doc['location'].lon)",
    " +
                    "          "lang":"expression",
    " +
                    "          "params":{"lat":" + latitude.toString() + ","lon":" + longitude.toString() + "}
    " +
                    "        
    " +
                    "      }
    " +
                    "    }
    " +
                    "  },
    " +
                    "  "query": {
    " +
                    "    "function_score": {
    " +
                    "      "query": {
    " +
                    "        "bool": {
    " +
                    "        "must": [
    " +
                    "        {"match": {"name": {"query": "" + keyword +  "","boost": 0.1}}},
    " +
                    "        {"term": {"seller_disabled_flag": 0}}
    " +
                    "      ]}},
    " +
                    "      "functions": [
    " +
                    "        {
    " +
                    "          "gauss": {
    " +
                    "            "location": {
    " +
                    "              "origin": "" + latitude.toString() + "," + longitude.toString() +  "",
    " +
                    "              "scale": "100km",
    " +
                    "              "offset": "0km",
    " +
                    "              "decay": 0.5
    " +
                    "            }
    " +
                    "          },
    " +
                    "          "weight": 9
    " +
                    "        },
    " +
                    "        {
    " +
                    "          "field_value_factor": {
    " +
                    "            "field": "remark_score"
    " +
                    "          },
    " +
                    "          "weight": 0.2
    " +
                    "        },
    " +
                    "        {
    " +
                    "          "field_value_factor": {
    " +
                    "            "field": "seller_remark_score"
    " +
                    "          },
    " +
                    "          "weight": 0.1
    " +
                    "        }
    " +
                    "      ],
    " +
                    "      "score_mode": "sum",
    " +
                    "      "boost_mode": "replace"
    " +
                    "    }
    " +
                    "  }
    " +
                    "  , "sort": [
    " +
                    "    {
    " +
                    "      "_score": {
    " +
                    "        "order": "desc"
    " +
                    "      }
    " +
                    "    }
    " +
                    "  ]
    " +
                    "  
    " +
                    "  
    " +
                    "}";
            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;
        }
  • 相关阅读:
    [leetcode] Rotate Image
    [leetcode] Jump Game II
    [leetcode] Permutations II
    [leetcode] Permutations
    [leetcode] Wildcard Matching
    [leetcode] Multiply Strings
    [leetcode] Trapping Rain Water
    [leetcode] First Missing Positive
    [leetcode] Combination Sum II
    [leetcode] Combination Sum
  • 原文地址:https://www.cnblogs.com/yaohaitao/p/12643964.html
Copyright © 2020-2023  润新知