elastic客户端TransportClient的使⽤
关于TransportClient,elastic计划在Elasticsearch 7.0中弃⽤TransportClient,并在8.0中完全删除它。后⾯,应该使⽤Java⾼级REST 客户端,它执⾏HTTP请求⽽不是序列化的Java请求。Java客户端主要⽤途有:
(1)在现有集上执⾏标准索引,获取,删除和搜索操作
(2)在正在运⾏的集上执⾏管理任务
获取Elasticsearch客户端最常⽤⽅法是创建连接到集的TransportClient。
maven依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.4.3</version>
</dependency>
客户端必须具有与集中的节点相同的主要版本(例如2.x或5.x)。客户端可以连接到具有不同次要版本(例如2.3.x)的集,但可能不⽀持新功能。理想情况下,客户端应具有与集相同的版本。此博客⽬前正在使⽤的版本是6.4.3。
获取TransportClient
TransportClient使⽤传输模块远程连接到Elasticsearch集。它不加⼊集,⽽只是获取⼀个或多个初始传输地址,并在每个操作上以循环⽅式与它们通信。
import org.ansport.TransportClient;
import org.de.DiscoveryNode;
import org.elasticsearchmon.settings.Settings;
import ansport.TransportAddress;
import ansport.client.PreBuiltTransportClient;
import java.InetAddress;
import java.UnknownHostException;
public class Elasticsearch {
public static void main(String[] args) throws UnknownHostException {
//on startup
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new ByName("127.0.0.1"), 9300));
//继续添加其他地址
//on shutdown
client.close();
}
}
如果出现:
说明需要配置⽇志
maven依赖
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.1</version>
</dependency>
然后再resources⾥⾯添加log4j2.properties,内容如下:
rootLogger.level = info
f = console
如果出现"Exception in thread "main" java.lang.NoSuchMethodError:
org.apache.logging.log4j.Logger.debug(Ljava/lang/String;Ljava/lang/Object;)", 则说明版本冲突,或者引的包是错的。
请注意,如果使⽤集名称不是默认的“elasticsearch”,则必须设置集名称,通过对Settings经⾏设置:
Settings settings = Settings.builder()
.put("cluster.name", "myClusterName").build();
TransportClient client = new PreBuiltTransportClient(settings);
//Add transport addresses and do something with
如果开启嗅探功能,即⾃动检测集内其他的节点和新加⼊的节点,不需要全部都是⽤addTransportAddress添加,设置如下:Settings settings = Settings.builder()
.put("ansport.sniff", true).build();
TransportClient client = new PreBuiltTransportClient(settings);
Document APIs
Single document APIs
(1)Index api
import com.JsonProcessingException;
import org.elasticsearch.action.index.IndexResponse;
import org.ansport.TransportClient;
import org.elasticsearchmon.settings.Settings;
import ansport.TransportAddress;
import nt.XContentType;
import st.RestStatus;
import ansport.client.PreBuiltTransportClient;
import java.InetAddress;
import java.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class Elasticsearch {
public static void main(String[] args) throws UnknownHostException, JsonProcessingException {
/
/on startup
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new ByName("127.0.0.1"), 9300));
//继续添加其他地址
Map<String, Object> json = new HashMap<String, Object>();
json.put("user", "kimchy");
json.put("postDate", new Date());
json.put("message", "trying out Elasticsearch");
// index--twitter type--_doc id--1
IndexResponse indexResponse = client.prepareIndex("twitter", "_doc", "1").setSource(json, XContentType.JSON).get();
// Index name
String _index = Index();
// Type name
String _type = Type();
// Document ID (generated or not)
String _id = Id();
// Version (if it's the first time you index this document, you will get: 1)
long _version = Version();
// status has stored current instance statement.
RestStatus status = indexResponse.status();
//on shutdown
client.close();
}
}
实现了数据的插⼊
(2)GET API
get API允许根据其id从索引中获取类型化的JSON⽂档。以下⽰例从名为twitter的索引中获取JSON⽂档,该类型名为_doc`,id值为1:import com.JsonProcessingException;
import org.GetRequestBuilder;
import org.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.ansport.TransportClient;
import org.elasticsearchmon.settings.Settings;
import ansport.TransportAddress;
import nt.XContentType;
import st.RestStatus;
import ansport.client.PreBuiltTransportClient;
import java.InetAddress;
import java.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class Elasticsearch {
public static void main(String[] args) throws UnknownHostException, JsonProcessingException { //on startup
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new ByName("127.0.0.1"), 9300));
//继续添加其他地址
GetResponse documentFields = client.prepareGet("twitter", "_doc", "1").get();
System.out.Index());
System.out.Type());
System.out.Id());
System.out.SourceAsString());
//on shutdown
client.close();
}
}
输出结果:
(3)DELETE API
import com.JsonProcessingException;
import org.elasticsearch.action.delete.DeleteResponse;
import org.GetRequestBuilder;
import org.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.ansport.TransportClient;
import org.elasticsearchmon.settings.Settings;
import ansport.TransportAddress;
import nt.XContentType;log4j2 console
import st.RestStatus;
import ansport.client.PreBuiltTransportClient;
import java.InetAddress;
import java.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class Elasticsearch {
public static void main(String[] args) throws UnknownHostException, JsonProcessingException { //on startup
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new ByName("127.0.0.1"), 9300));
//继续添加其他地址
DeleteResponse response = client.prepareDelete("twitter", "_doc", "1").get();
System.out.String());
//on shutdown
client.close();
}
}
结果如下:
(4)Delete By Query API
import com.JsonProcessingException;
import org.elasticsearch.action.delete.DeleteResponse;
import org.GetRequestBuilder;
import org.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.ansport.TransportClient;
import org.elasticsearchmon.settings.Settings;
import ansport.TransportAddress;
import nt.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.index.BulkByScrollResponse;
import org.index.DeleteByQueryAction;
import st.RestStatus;
import ansport.client.PreBuiltTransportClient;
import java.InetAddress;
import java.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class Elasticsearch {
public static void main(String[] args) throws UnknownHostException, JsonProcessingException {
//on startup
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new ByName("127.0.0.1"), 9300));
/
/继续添加其他地址
BulkByScrollResponse response = wRequestBuilder(client)
.filter(QueryBuilders.matchQuery("user", "kimchy"))
.source("twitter")
.get();
long deleted = Deleted();
//on shutdown
client.close();
}
}
以刚才那条index->twitter为例,此api先查询出满⾜条件的所有index,然后调⽤getDeleted函数删除相关的数据。
(5)Update API
可以使⽤prepareUpdate()⽅法
import com.JsonProcessingException;
import org.elasticsearch.action.delete.DeleteResponse;
import org.GetRequestBuilder;
import org.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.ansport.TransportClient;
import org.elasticsearchmon.settings.Settings;
import ansport.TransportAddress;
import nt.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.index.BulkByScrollResponse;
import org.index.DeleteByQueryAction;
import st.RestStatus;
import ansport.client.PreBuiltTransportClient;
import java.io.IOException;
import java.InetAddress;
import java.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import static nt.XContentFactory.jsonBuilder;
public class Elasticsearch {
public static void main(String[] args) throws IOException {
//on startup
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new ByName("127.0.0.1"), 9300));
//继续添加其他地址
client.prepareUpdate("twitter", "_doc", "1")
.setDoc(jsonBuilder()
.startObject()
.field("user", "chenmz")
.
endObject())
.get();
//on shutdown
client.close();
}
}
⽤kibana查询后:
发现名字已经发⽣改变,更改成功。
Multi-document APIs
(1)Multi Get API
multi get API允许根据索引和id获取⽂档列表,往elastic中添加id为2的document,然后查询:
import com.JsonProcessingException;
import org.elasticsearch.action.delete.DeleteResponse;
import org.GetRequestBuilder;
import org.GetResponse;
import org.MultiGetItemResponse;
import org.MultiGetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.ansport.TransportClient;
import org.elasticsearchmon.settings.Settings;
import ansport.TransportAddress;
import nt.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.index.BulkByScrollResponse;
import org.index.DeleteByQueryAction;
import st.RestStatus;
import ansport.client.PreBuiltTransportClient;
import java.io.IOException;
import java.InetAddress;
import java.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import static nt.XContentFactory.jsonBuilder;
public class Elasticsearch {
public static void main(String[] args) throws IOException {
//on startup
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new ByName("127.0.0.1"), 9300));
//继续添加其他地址
MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
.add("twitter", "_doc", "1", "2")
.get();
for (MultiGetItemResponse itemResponse : multiGetItemResponses) {
GetResponse response = Response();
if (response.isExists()) {
String json = SourceAsString();
System.out.println(json);
}
}
//on shutdown
client.close();
}
}
运⾏结果:
(2)Bulk API
批量API允许在单个请求中索引和删除多个⽂档。以下演⽰增加多个索引。import com.JsonProcessingException;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.GetRequestBuilder;
import org.GetResponse;
import org.MultiGetItemResponse;
import org.MultiGetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.ansport.TransportClient;
import org.elasticsearchmon.settings.Settings;
import ansport.TransportAddress;
import nt.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.index.BulkByScrollResponse;
import org.index.DeleteByQueryAction;
import st.RestStatus;
import ansport.client.PreBuiltTransportClient;
import java.io.IOException;
import java.InetAddress;
import java.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import static nt.XContentFactory.jsonBuilder;
public class Elasticsearch {
public static void main(String[] args) throws IOException {
//on startup
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new ByName("127.0.0.1"), 9300));
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论