博客
关于我
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/

你可能感兴趣的文章
mysql网站打开慢问题排查&数据库优化
查看>>
mysql网络部分代码
查看>>
mysql联合索引 where_mysql联合索引与Where子句优化浅析
查看>>
mysql联合索引的最左前缀匹配原则
查看>>
mysql自动化同步校验_Shell: 分享MySQL数据同步+主从复制自动化脚本_20190313_七侠镇莫尛貝...
查看>>
Mysql自增id理解
查看>>
mysql自增id超大问题查询
查看>>
MySQL自定义变量?学不废不收费
查看>>
MySQL自带information_schema数据库使用
查看>>
MySQL获取分组后的TOP 1和TOP N记录
查看>>
mysql虚拟列表_动态网页制作-官方版合集下载-多特
查看>>
MySQL蜜罐反制获取攻击者信息
查看>>
Mysql表创建外键报错
查看>>
mysql表格调取数据库信息_MySQL™ 参考手册(获取有关数据库和表的信息)
查看>>
mysql表检查分析优化
查看>>
WARN: Establishing SSL connection without server‘s identity verification is not recommended.
查看>>
MySQL视图
查看>>
MySQL视图
查看>>
Mysql视图、变量、存储过程、函数
查看>>
Mysql视图、触发器、事务、储存过程、函数
查看>>