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

你可能感兴趣的文章
mysql5.7免费下载地址
查看>>
mysql5.7命令总结
查看>>
mysql5.7安装
查看>>
mysql5.7性能调优my.ini
查看>>
MySQL5.7新增Performance Schema表
查看>>
Mysql5.7深入学习 1.MySQL 5.7 中的新增功能
查看>>
Webpack 之 basic chunk graph
查看>>
Mysql5.7版本单机版my.cnf配置文件
查看>>
mysql5.7的安装和Navicat的安装
查看>>
mysql5.7示例数据库_Linux MySQL5.7多实例数据库配置
查看>>
Mysql8 数据库安装及主从配置 | Spring Cloud 2
查看>>
mysql8 配置文件配置group 问题 sql语句group不能使用报错解决 mysql8.X版本的my.cnf配置文件 my.cnf文件 能够使用的my.cnf配置文件
查看>>
MySQL8.0.29启动报错Different lower_case_table_names settings for server (‘0‘) and data dictionary (‘1‘)
查看>>
MYSQL8.0以上忘记root密码
查看>>
Mysql8.0以上重置初始密码的方法
查看>>
mysql8.0新特性-自增变量的持久化
查看>>
Mysql8.0注意url变更写法
查看>>
Mysql8.0的特性
查看>>
MySQL8修改密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
查看>>
MySQL8修改密码的方法
查看>>