所以我只是想通过indice
在我的java transport client api
中添加数据。我的代码运行无任何异常。
indices
,它也显示了这一点。 docs
插入我的indice
中,称为logs
下面是我的代码:
public static void main(String[] args) {
try {
ElasticSearchMain es = new ElasticSearchMain();
ElasticSearchMain.configureClient();
JSONObject data = new JSONObject();
data.put("serverip", "bhavik");
data.put("classname", "bhavik");
data.put("methodname", "bhavik");
data.put("exception", "bhavik");
data.put("logexception", "4896681231231232");
data.put("timestamp", "1900-00-00");
es.setIndex(data.toString(), "logs");
} catch (Exception e) {
e.printStackTrace();
}
}
public IndexRequestBuilder setIndex(String data,String IndexName){
try{
return client.prepareIndex(IndexName, "event").setSource(data);
}catch(Exception e){
e.printStackTrace();
}
return null;
}
public static void configureClient(){
try{
if(client==null){
String address = "localhost";
int port = 9300;
BasicConfigurator.configure();
client = TransportClient.builder().build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(address), port));
String[] indices = client.admin().indices().getIndex(new GetIndexRequest()).actionGet().getIndices();
for (String s : indices) {
System.out.println("indice ->> " + s);
}
}
}catch(Exception e ){
e.printStackTrace();
EmgrLog.AppendExceptionToLog(e);
}
}
指标映射:
PUT logs
{
"mappings": {
"event": {
"properties": {
"serverip": {
"type": "integer",
"index": "not_analyzed"
},
"classname": {
"type": "string",
"analyzer": "english"
},
"methodname": {
"type": "string",
"index": "not_analyzed"
},
"exception": {
"type": "string",
"index": "not_analyzed"
},
"logexception": {
"type": "string"
},
"timestamp":{
"type": "date"
}
}
}
}
}
最佳答案
此代码:
public IndexRequestBuilder setIndex(String data,String IndexName){
try{
return client.prepareIndex(IndexName, "event").setSource(data);
}catch(Exception e){
e.printStackTrace();
}
return null;
}
返回一个“请求生成器”,但是此请求从不构建,也不执行,从逻辑上讲,没有任何结果。
要提交请求,您必须将其发送到elasticsearch实例。
Elasticsearch JavaAPI documentation提出以下代码:
IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
.setSource(jsonBuilder()
.startObject()
.field("user", "kimchy")
.field("postDate", new Date())
.field("message", "trying out Elasticsearch")
.endObject()
)
.get();
请注意,代码片段末尾的
get()
是触发调用的原因。