elasticsearch学习javaAPI:es的增删改查

来源:互联网 发布:js数组去重系统方法 编辑:程序博客网 时间:2024/06/04 17:51

1.环境要求:

1.jdk1.8以上

2.Maven依赖

<dependencies>    <dependency>    <groupId>org.elasticsearch.client</groupId>    <artifactId>transport</artifactId>    <version>5.2.2</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>  </dependencies>

2.通过TransportClient进行增上改查的业务

package com.roncoo.es.score.first;import java.io.IOException;import java.net.InetAddress;import org.elasticsearch.action.delete.DeleteResponse;import org.elasticsearch.action.get.GetResponse;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;public class ProductCURD {@SuppressWarnings({ "unchecked", "resource" })public static void main(String[] args) throws Exception {//1.构建clientSettings settings = Settings.builder().put("cluster.name", "my-application").build();TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"),9300));//2.进行操作//2.1增加,创建一个商品//addProdect(client);//2.2查询,获取商品//getProduct(client);//2.3修改,修改商品//updateProduct(client);//2.4删除,删除商品//deleteProduct(client);//3.关闭连接client.close();}/** * 创建一个商品 * @param client * @throws IOException  */private static void addProdect(TransportClient client) throws IOException {IndexResponse response = client.prepareIndex("shop", "product", "1").setSource(XContentFactory.jsonBuilder().startObject().field("name", "Thinking in java").field("price", "99").field("author","jack").field("country", "us").endObject()).get();System.out.println(response.getResult());}/** * 查看商品信息 * @param client */private static void getProduct(TransportClient client) {GetResponse response = client.prepareGet("shop","product","1").get();System.out.println(response.getSourceAsString());}/** * 修改商品 * @param client * @throws IOException  */private static void updateProduct(TransportClient client) throws IOException {UpdateResponse response = client.prepareUpdate("shop","product","1").setDoc(XContentFactory.jsonBuilder().startObject().field("price", "9.9").endObject()).get();System.out.println(response.getResult());}/** * 删除 一个商品 * @param client */private static void deleteProduct(TransportClient client) {DeleteResponse response = client.prepareDelete("shop", "product", "1").get();System.out.println(response.getResult());}}

原创粉丝点击