博客
关于我
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中出现update-alternatives: 错误: 候选项路径 /etc/mysql/mysql.cnf 不存在 dpkg: 处理软件包 mysql-server-8.0的解决方法(全)
查看>>
MySQL中地理位置数据扩展geometry的使用心得
查看>>
Mysql中存储引擎简介、修改、查询、选择
查看>>
mysql中实现rownum,对结果进行排序
查看>>
mysql中对于数据库的基本操作
查看>>
mysql中的 +号 和 CONCAT(str1,str2,...)
查看>>
MySql中的concat()相关函数
查看>>
mysql中的concat函数,concat_ws函数,concat_group函数之间的区别
查看>>
MySQL中的count函数
查看>>
MySQL中的DB、DBMS、SQL
查看>>
MySQL中的DECIMAL类型:MYSQL_TYPE_DECIMAL与MYSQL_TYPE_NEWDECIMAL详解
查看>>
MySQL中的GROUP_CONCAT()函数详解与实战应用
查看>>
MySQL中的IO问题分析与优化
查看>>
MySQL中的ON DUPLICATE KEY UPDATE详解与应用
查看>>
mysql中的rbs,SharePoint RBS:即使启用了RBS,内容数据库也在不断增长
查看>>
mysql中的undo log、redo log 、binlog大致概要
查看>>
Mysql中的using
查看>>
MySQL中的关键字深入比较:UNION vs UNION ALL
查看>>
MYSQL中频繁的乱码问题终极解决
查看>>
Mysql主从不同步
查看>>