1.引入pom文件:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
复制代码
注意client版本一定和启动es服务版本对应,否则调用会出现错误,并且要增加log4j2.properties,否则也会报错
2.代码操作:
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
/** *
- @author brucezhang
*/ public class EsCrud {
public static TransportClient transportClient;
@BeforeClass
public static void start(){
Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
try {
transportClient = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
@Test
public void createIndex() throws IOException{
IndexResponse indexResponse = transportClient.prepareIndex("vhddata", "wxdata","1").
setSource(XContentFactory.jsonBuilder().startObject().
field("name", "zpl").endObject())
.get();
System.out.println(indexResponse.getResult());
}
@Test
public void searchIndex(){
String sourceStr = transportClient.prepareGet("vhddata", "wxdata","1").get().getSourceAsString();
System.out.println(sourceStr);
}
@Test
public void updateIndex() throws IOException{
UpdateResponse response = transportClient.prepareUpdate("vhddata", "wxdata","1").
setDoc(XContentFactory.jsonBuilder().startObject().
field("name", "zplsfsf").endObject()).get();
System.out.println(response.getResult());
}
@Test
public void deleteIndex(){
DeleteResponse deleteResponse = transportClient.prepareDelete("vhddata", "wxdata","1").get();
System.out.println(deleteResponse.getResult());
}
@After
public void after(){
transportClient.close();
}
复制代码
}
3.欢迎关注我的公众号进行一起讨论学习: