java連接elasticsearch:查詢、添加數據


導入jar包

        <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
        </dependency>

初始化TransportClient對象

    /**
     *  初始化TransportClient對象, 這里只配置了單個節點,例如100.100.0.1:8090
     */
    private TransportClient initClient() throws UnknownHostException {
        String node = esSetting.getClusterNodes();
        int index = node.indexOf(":");
        String host = node.substring(0, index);
        int port = Integer.valueOf(node.substring(index + 1));
        
        Settings settings = Settings.builder()
                //elasticsearch節點名稱
                .put("cluster.name", esSetting.getClusterName())
                .put("client.transport.sniff", true).build();
        
        InetAddress address = InetAddress.getByName(host);
        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(new InetSocketTransportAddress(address, port));
        
        return client;
    }

查詢:

        //查詢,根據數據中date字段查詢, 這里是最常用的boolQuery示例,可以通過must、must_not、filter等方法設定查詢條件
        QueryBuilder queryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.rangeQuery("date").gte("2018-11-08T00:00:00.000Z")
                        .lt("2018-11-09T00:00:00.000Z"));
        
        //elasticsearch索引及類型,對應數據庫中數據庫和表
        String index = "index";
        String type = "type";
        SearchResponse response = client.prepareSearch(index)
                .setTypes(type).addSort("date", SortOrder.ASC)
                .setSize(1000).setQuery(queryBuilder).execute()
                .actionGet();
        
        long total = response.getHits().getTotalHits();

寫入:

        try {
            XContentBuilder builder = XContentFactory.jsonBuilder()
                    .startObject().field("date", "2018-11-08T00:00:00.000Z")
                    .field("cost", 10);
            builder.endObject();
            IndexResponse response = client
                    .prepareIndex(index, type)
                    .setSource(builder).get();
        } catch (Exception e) {
            e.printStackTrace();
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM