这里描述操作elasticsearch采用TransportClient这种方式,官方明确表示在ES 7.0版本中将弃用TransportClient客户端,且在8.0版本中完全移除它.

记录一些常用的方法:

官方文档:

TransportClient

/**
* 简单查询es 指定index type id
*/
@Test
public void search() throws UnknownHostException {
//获取client
Settings settings= Settings.builder().put("cluster.name","my-application").build();
TransportClient transportClient=new PreBuiltTransportClient(settings);
transportClient.addTransportAddress(new
TransportAddress(InetAddress.getByName("localhost"),9300));
// 发起请求得到响应
GetResponse response=transportClient.prepareGet("index3","user3","10").get();
System.out.println(response.getSource());
}
/**
* 增加文档
*/
@Test
public void insert() throws Exception{
Settings settings= Settings.builder().put("cluster.name","my-application").build();
TransportClient client=new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300));
XContentBuilder contentBuilder= XContentFactory.jsonBuilder()
.startObject()
.field("catid","22")
.field("classify",54)
.field("author","ssve")
.field("id","1")
.field("title","菜鸟成长记")
.endObject();
IndexResponse indexResponse = client.prepareIndex("index3", "user3", "10")
.setSource(contentBuilder)
.get();
System.out.println(indexResponse.status());
}
/**
* 删除文档
*/
@Test
public void delete() throws Exception{
Settings settings=Settings.builder().put("cluster.name","my-application").build();
TransportClient client=new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300)); DeleteResponse deleteResponse = client.prepareDelete("index3", "user3", "10").get(); System.out.println(deleteResponse.status());
}
/**
* 修改文档
*/
@Test
public void update() throws Exception{
Settings settings=Settings.builder().put("cluster.name","my-application").build();
TransportClient client=new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300)); UpdateRequest request=new UpdateRequest();
XContentBuilder contentBuilder=XContentFactory.jsonBuilder()
.startObject()
.field("id","555")
.endObject();
request.index("index3")
.type("user3")
.id("10")
.doc(contentBuilder);
UpdateResponse updateResponse = client.update(request).get(); System.out.println(updateResponse.status());
}
/**
*upsert使用 如有存在对应文档就修改 不存在就新增 需要指定修改的文档 和新增的文档
*/
@Test
public void upsert() throws IOException, ExecutionException, InterruptedException {
Settings settings=Settings.builder().put("cluster.name","my-application").build();
TransportClient client=new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300)); XContentBuilder builder=XContentFactory.jsonBuilder()
.startObject()
.field("catid","22")
.field("classify",54)
.field("author","zhang")
.field("id","10")
.field("title","菜鸟成长记")
.endObject();
UpdateRequest request=new UpdateRequest();
IndexRequest indexRequest=new IndexRequest();
indexRequest.index("index3")
.type("user3")
.id("11")
.source(builder);
request.index("index3")
.type("user3")
.id("11")
.doc(new XContentFactory().jsonBuilder()
.startObject()
.field("id","i love you")
.endObject()
).upsert(indexRequest);
UpdateResponse updateResponse = client.update(request).get(); System.out.println(updateResponse.status()); }
/**
*
* 批量查询 multiGet
*/
@Test
public void multiGet() throws Exception{
Settings settings=Settings.builder().put("cluster.name","my-application").build();
TransportClient client=new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300)); MultiGetRequest request=new MultiGetRequest();
request.add("index3","user3","11");
request.add("index3","user3","10");
request.add("index3","user3","13");
request.add("index3","user3","14");
MultiGetResponse multiGetItemResponses = client.multiGet(request).get(); for (MultiGetItemResponse response:multiGetItemResponses) {
System.out.println(response.getResponse().getSourceAsString());
} }
/**
*
* bulk实现批量增删改操作。
*/
@Test
public void bulk() throws Exception{
Settings settings=Settings.builder().put("cluster.name","my-application").build();
TransportClient client=new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300)); BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
IndexRequest request=new IndexRequest();
request.index("index3")
.type("user3")
.id("13")
.source(XContentFactory.jsonBuilder()
.startObject()
.field("catid","85")
.field("classify","85")
.field("author","宇宙无敌")
.field("id","漫威")
.field("title","漫威")
.endObject()); IndexRequest request1=new IndexRequest();
request1.index("index3")
.type("user3")
.id("14")
.source(XContentFactory.jsonBuilder()
.startObject()
.field("catid","55")
.field("classify","85")
.field("author","宇宙无敌")
.field("id","漫威")
.field("title","漫威")
.endObject());
bulkRequestBuilder.add(request1);
bulkRequestBuilder.add(request);
BulkResponse bulkItemResponses = bulkRequestBuilder.get();
System.out.println(bulkItemResponses.status()); }
/**
*
* 使用query查询 match_all 查询所有
*/
@Test
public void query() throws Exception{
Settings settings=Settings.builder().put("cluster.name","my-application").build();
TransportClient client=new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300)); MatchAllQueryBuilder builder= QueryBuilders.matchAllQuery(); SearchRequestBuilder index3 = client.prepareSearch("index3")
.setQuery(builder)
.setSize(5);
SearchResponse searchResponse = index3.get();
SearchHits hits = searchResponse.getHits();
for (SearchHit hit:hits) {
System.out.println(hit.getSourceAsString());
}
}
/**
*
* 使用query查询 match 查询
*/
@Test
public void matchQuery() throws Exception{
Settings settings=Settings.builder().put("cluster.name","my-application").build();
TransportClient client=new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300)); MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", "爱");
SearchRequestBuilder index = client.prepareSearch("index3").setQuery(matchQueryBuilder).setSize(10);
SearchHits hits = index.get().getHits();
for (SearchHit hit:hits
) {
System.out.println(hit.getSourceAsString());
}
}
/**
*
* 使用query查询 mutilMatch 查询
*/
@Test
public void mutilMatchQuery() throws Exception{
Settings settings=Settings.builder().put("cluster.name","my-application").build();
TransportClient client=new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300)); MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("周星驰影帝", "author","title");
SearchRequestBuilder index = client.prepareSearch("index3").setQuery(multiMatchQueryBuilder).setSize(10);
SearchHits hits = index.get().getHits();
for (SearchHit hit:hits
) {
System.out.println(hit.getSourceAsString());
}
} /**
*
* 使用query查询 termheterms查询
*/
@Test
public void termsMatchQuery() throws Exception{
Settings settings=Settings.builder().put("cluster.name","my-application").build();
TransportClient client=new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300)); TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("title", "周星驰", "影帝");
SearchRequestBuilder index = client.prepareSearch("index3").setQuery(termsQueryBuilder).setSize(10);
SearchHits hits = index.get().getHits();
for (SearchHit hit:hits
) {
System.out.println(hit.getSourceAsString());
}
} /**
*
* 使用query查询 范围 通配符 前缀 模糊查询
*/
@Test
public void query1() throws Exception{
Settings settings=Settings.builder().put("cluster.name","my-application").build();
TransportClient client=new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300));
//范围查询
//QueryBuilder queryBuilder = QueryBuilders.rangeQuery("classify").from("1").to("40"); //通配符查询 * 零个或多个
// QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("author","周*"); //前缀查询
// QueryBuilder queryBuilder = QueryBuilders.prefixQuery("author","周"); //模糊查询 查询类型的
// QueryBuilder queryBuilder = QueryBuilders.fuzzyQuery("id","aac"); //id查询 QueryBuilder queryBuilder = QueryBuilders.idsQuery().addIds("1","2","4");
SearchRequestBuilder index = client.prepareSearch("index3").setQuery(queryBuilder).setSize(10);
SearchHits hits = index.get().getHits();
for (SearchHit hit:hits
) {
System.out.println(hit.getSourceAsString());
}
} /**
*
* 聚合查询
*/
@Test
public void aggregation() throws Exception{
Settings settings=Settings.builder().put("cluster.name","my-application").build();
TransportClient client=new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300)); AggregationBuilder aggregationBuilder= AggregationBuilders.max("max").field("id"); SearchResponse index3 = client.prepareSearch("index3").addAggregation(aggregationBuilder).get(); Max max = index3.getAggregations().get("max"); System.out.println(max.getValue());
}
/**
*
* queryString
*/
@Test
public void queryString() throws Exception{
Settings settings=Settings.builder().put("cluster.name","my-application").build();
TransportClient client=new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300));
// + 代表必须有 -代表没有
QueryBuilder queryBuilder=QueryBuilders.queryStringQuery("+周星驰 -sss");
SearchRequestBuilder index3 = client.prepareSearch("index3")
.setQuery(queryBuilder)
.setSize(10);
SearchResponse searchResponse = index3.get();
for (SearchHit hit:searchResponse.getHits()) {
System.out.println(hit.getSourceAsString());
}
} /**
*
* 组合查询
*/
@Test
public void boolQuery() throws Exception{
Settings settings=Settings.builder().put("cluster.name","my-application").build();
TransportClient client=new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300));
QueryBuilder queryBuilder=QueryBuilders.boolQuery()
.must(QueryBuilders.matchQuery("author","周星驰"))
.mustNot(QueryBuilders.matchQuery("title","梁朝伟"))
.should(QueryBuilders.matchQuery("title","影帝"))
.filter(QueryBuilders.rangeQuery("id").gte("1")); SearchRequestBuilder index3 = client.prepareSearch("index3")
.setQuery(queryBuilder)
.setSize(10);
SearchResponse searchResponse = index3.get();
for (SearchHit hit:searchResponse.getHits()) {
System.out.println(hit.getSourceAsString());
}
}

Elasticsearch(Transport Client)常用操作的更多相关文章

  1. ElasticSearch之映射常用操作

    本文案例操作,建议先阅读我之前的文章<ElasticSearch之安装及基本操作API> Mapping (映射)类似关系型数据库中的表的结构定义.我们将数据以 JSON 格式存入到 El ...

  2. zookeeper client 常用操作

    #获取权限(类似于登陆) addauth digest admin-user:admin-password #查看权限 getAcl /collections/meixin_product/state ...

  3. elasticsearch系列七:ES Java客户端-Elasticsearch Java client(ES Client 简介、Java REST Client、Java Client、Spring Data Elasticsearch)

    一.ES Client 简介 1. ES是一个服务,采用C/S结构 2. 回顾 ES的架构 3. ES支持的客户端连接方式 3.1 REST API ,端口 9200 这种连接方式对应于架构图中的RE ...

  4. Elasticsearch Java client(ES Client 简介、Java REST Client、Java Client、Spring Data Elasticsearch)

    elasticsearch系列七:ES Java客户端-Elasticsearch Java client(ES Client 简介.Java REST Client.Java Client.Spri ...

  5. [No000091]SVN学习笔记2-TortoiseSVN Client初级操作update(获取)、commit(提交)

    SVN简介: 为什么要使用SVN? 程序员在编写程序的过程中,每个程序员都会生成很多不同的版本,这就需要程序员有效的管理代码,在需要的时候可以迅速,准确取出相应的版本. Subversion是什么? ...

  6. Elasticsearch Java Client连接池

    按照Elasticsearch API,在Java端使用是ES服务需要创建Java Client,但是每一次连接都实例化一个client,对系统的消耗很大,即使在使用完毕之后将client close ...

  7. Elasticsearch本地环境安装和常用操作

    本篇文章首发于我的头条号Elasticsearch本地环境安装和常用操作,欢迎关注我的头条号和微信公众号"大数据技术和人工智能"(微信搜索bigdata_ai_tech)获取更多干 ...

  8. Elasticsearch(ES)API 增删查改常用操作

    常用操作 查询所有数据 POST http://192.168.97.173:27009/logstash_test_2018/doc/_search { "query": { & ...

  9. MongoDB副本集的常用操作及原理

    本文是对MongoDB副本集常用操作的一个汇总,同时也穿插着介绍了操作背后的原理及注意点. 结合之前的文章:MongoDB副本集的搭建,大家可以在较短的时间内熟悉MongoDB的搭建和管理. 下面的操 ...

随机推荐

  1. 转-C++之手写strcpy

    转自:strcpy函数的实现 知strcpy函数的原型是: char *strcpy(char *dst, const char *src); 实现strcpy函数 解释为什么要返回char * 假如 ...

  2. java url中文参数乱码

    String city=new String(city_name.getBytes("ISO-8859-1"), "UTF-8");

  3. (3)Redis conifg

    redis.windows-service.conf      Redis-x64-3.2.100 # Redis configuration file example # Note on units ...

  4. Dubbo入门到精通学习笔记(四):持续集成管理平台之Maven私有库和本地库的安装与配置

    文章目录 介绍 Maven私有库和本地库的安装与配置 Nexus安装 Nexus 配置(登录后) 介绍 如果构建的Maven项目本地仓库没有对应的依赖包,那么就会去Nexus私服去下载, 那么如果Ne ...

  5. HDU 5443 The Water Problem (ST算法)

    题目链接:HDU 5443 Problem Description In Land waterless, water is a very limited resource. People always ...

  6. csv 基本操作, 报错解决(UnicodeEncodeError: 'utf-8' codec can't encode characters in position 232-233: surrogates not allowed)

    最常用的一种方法,利用pandas包 import pandas as pd #任意的多组列表 a = [1,2,3] b = [4,5,6] #字典中的key值即为csv中列名 dataframe ...

  7. php的生命周期的概述

    1. PHP是随着WEB服务器(apache)的启动而运行的: 2. PHP通过mod_php5.so()模块和服务器(apache)相连 3. PHP总共有三个模块:内核.Zend引擎.以及扩展层: ...

  8. box-shadow单侧投影,双侧投影,不规则图案投影

    底部投影box-shadow: 0 5px 4px -4px black; 底部右侧投影 3px 3px 6px -3px black 两侧投影 box-shadow: 7px 0 7px -7px ...

  9. 微信小程序のwxml列表渲染

    列表渲染存在的意义 以电商为例,我们希望渲染5个商品,而又希望容易改变,我们就要在wxml中动态添加. <view> <block wx:for="{{products}} ...

  10. react-router v4 理解

    1.Router (1)最基础的路由器,必须有history属性 (2)BrowserRouter和HashRouter都是由Router组件扩展而来 2.BrowserRouter (1)Brows ...