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
@Overridepublic 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;}
原文地址:https://www.cnblogs.com/yaohaitao/p/12643964.html
时间: 2024-11-12 15:08:23