博客
关于我
java连接elasticsearch:查询、添加数据
阅读量:467 次
发布时间:2019-03-06

本文共 2049 字,大约阅读时间需要 6 分钟。

导入jar包

org.elasticsearch.client
transport

初始化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();        }

 

转载地址:http://fkdbz.baihongyu.com/

你可能感兴趣的文章
Nacos如何实现Raft算法与Raft协议原理详解
查看>>
Nacos安装教程(非常详细)从零基础入门到精通,看完这一篇就够了
查看>>
Nacos实战攻略:从入门到精通,全面掌握服务治理与配置管理!(上)
查看>>
Nacos实战攻略:从入门到精通,全面掌握服务治理与配置管理!(下)
查看>>
Nacos心跳机制实现快速上下线
查看>>
nacos报错com.alibaba.nacos.shaded.io.grpc.StatusRuntimeException: UNAVAILABLE: io exception
查看>>
nacos服务提供和发现及客户端负载均衡配置
查看>>
Nacos服务注册与发现demo
查看>>
Nacos服务注册与发现的2种实现方法!
查看>>
nacos服务注册和发现原理简单实现案例
查看>>
Nacos服务注册总流程(源码分析)
查看>>
nacos服务注册流程
查看>>
Nacos服务部署安装
查看>>
nacos本地可以,上服务器报错
查看>>
Nacos注册Dubbo(2.7.x)以及namespace配置
查看>>
Nacos注册中心有几种调用方式?
查看>>
nacos注册失败,Feign调用失败,feign无法注入成我们的bean对象
查看>>
nacos源码 nacos注册中心1.4.x 源码 nacos源码如何下载 nacos 客户端源码下载地址 nacos discovery下载地址(一)
查看>>
nacos源码 nacos注册中心1.4.x 源码 spring cloud alibaba 的discovery做了什么 nacos客户端是如何启动的(二)
查看>>
nacos源码 nacos注册中心1.4.x 源码 如何注册服务 发送请求,nacos clinet客户端心跳 nacos 注册中心客户端如何发送的心跳 (三)
查看>>