Elasticsearch 入门(一)

添加 Maven 依赖

	<dependency>
	    <groupId>org.elasticsearch.client</groupId>
	    <artifactId>elasticsearch-rest-high-level-client</artifactId>
	    <version>7.7.1</version>
	    <exclusions>
	        <exclusion>
	            <groupId>org.elasticsearch</groupId>
	            <artifactId>elasticsearch</artifactId>
	        </exclusion>
	    </exclusions>
	</dependency>
	
	<dependency>
	    <groupId>org.elasticsearch</groupId>
	    <artifactId>elasticsearch</artifactId>
	    <version>7.7.1</version>
	</dependency>

初始化客户端配置

	@Bean
	public RestHighLevelClient restHighLevelClient() {
	    RestClientBuilder builder = RestClient.builder(this.getHosts());
	    return new RestHighLevelClient(builder);
	}
	
	private HttpHost[] getHosts() {
	    String[] httpHosts = uris.split(",");
	    return Arrays.stream(httpHosts).map(item -> {
	        String[] nodes = item.split(":");
	        return new HttpHost(nodes[0], Integer.parseInt(nodes[1]));
	    }).toArray(HttpHost[]::new);
	}
spring.elasticsearch.uris=150.158.148.77:9200,150.158.148.78:9200,150.158.148.79:9200

查询数据

    @Autowired
    private RestHighLevelClient client;

    @Test
    void searchTest() throws IOException {
        SearchRequest searchRequest = new SearchRequest("index-test");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.termQuery("username", "tommy"));
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        // 请求状态
        RestStatus status = searchResponse.status();
        // 执行时间
        TimeValue took = searchResponse.getTook();
        // 搜索结果
        SearchHit[] searchHits = searchResponse.getHits().getHits();
        for (SearchHit searchHit : searchHits) {
            String sourceAsString = searchHit.getSourceAsString();
            System.out.println(sourceAsString);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值