欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

elasticsearch增删改查

程序员文章站 2022-07-05 08:01:22
...

用TransportClient操作elasticsearch进行增删改查 

import com.google.gson.Gson;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

/**
 * Created by liuxun on 2016/6/19.
 */
public class ElasticSearchHandler {
    /**
     * 通过TransportClient获取es Client
     * @return
     */
    public static Client getEmbeddedClient(){
        Client client = null;
        try {
            if (client!=null){
                return client;
            }
            Settings settings = Settings.settingsBuilder().put("cluster.name", "es-cluster").put("client.transport.sniff", true).build();
            client = TransportClient.builder().settings(settings).build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.38.131"), 9301))
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.38.131"), 9300));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }

    /**
     * 创建索引
     * @param client
     * @param json
     * @param index
     * @param type
     * @param valueId
     * @return
     */
    public static IndexResponse createIndex(Client client, Map<String, Object> json,String index,String type,String valueId){
        IndexResponse response = client.prepareIndex(index, type, valueId)
                .setSource(json)
                .get();
        return response;
    }

    /**
     * 根据valueid获取index
     * @param client
     * @param index
     * @param type
     * @param valueId
     * @return
     */
    public static GetResponse getIndex(Client client,String index,String type,String valueId){
        GetResponse response = client.prepareGet(index, type, valueId)
                .setOperationThreaded(false)
                .get();
        return response;
    }

    /**
     * 修改索引
     * @param client
     * @param index
     * @param type
     * @param valueId
     * @param name
     * @param value
     */
    public static void updateIndex(Client client,String index,String type,String valueId,String name,String value){
        try {
            UpdateRequest request = new UpdateRequest(index,type,valueId)
                    .doc(jsonBuilder().startObject().field(name, value).endObject());
            UpdateResponse response = client.update(request).get();
            System.out.println("update index result:"+response.getVersion());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    /**
     * 索引搜索
     * @param client
     * @param index
     * @param type
     * @param name
     * @param value
     */
    public static void searchIndex(Client client,String index,String type,String name,String value){
        SearchResponse response = client.prepareSearch(index)
                .setTypes(type)
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(QueryBuilders.matchPhraseQuery(name,value))
                .setPostFilter(QueryBuilders.existsQuery("name")) //过滤只有feids字段才返回结果的信息
                .setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18)) //范围过滤
                        .setFrom(0).setSize(10).setExplain(true) //分页
                        .execute()
                        .actionGet();
        SearchHits searchHits = response.getHits();
        System.out.println("search index length result:"+searchHits.hits().length);
        for(SearchHit hitFields:searchHits.getHits()){
            System.out.println("search index source result:"+hitFields.getSource().toString());
        }
    }

    /**
     * 删除索引
     * @param client
     * @param index
     * @param type
     * @param valueId
     */
    public static void deleteIndex(Client client,String index,String type,String valueId){
        Gson gson=new Gson();
        DeleteResponse response = client.prepareDelete(index, type, valueId).get();
        System.out.println("delete index result:"+gson.toJson(response));
    }
    public static void main(String[] args) {
        Client client=getEmbeddedClient();
        String index="user";String type="student";String valueid="3";
        Map<String, Object> json=new HashMap<String, Object>();
        json.put("name","格林");
        json.put("age",17);
        json.put("about","【格林折回球场同詹姆斯互相拥抱】勇士队主场以89-93不敌骑士队,总比分以3-4输掉了总决赛。勇士队前锋德雷蒙德-格林在返回更衣室后又重新回到人满为患的球场之上,挤开人群走向勒布朗-詹姆斯,二人拥抱致意,体育风范一展无遗。\n" +
                "\n" +
                "在赛后接受采访时,格林谈到:“当我走进更衣室之后,我坐了下来,他们(骑士)在手舞足蹈欢庆胜利,在那个时候,你无法去恭喜他们任何人。所以当我坐下来后,我知道我光坐在这里是不对的。那些家伙,他们赢得了冠军,我知道重回球场去恭喜他们打出了一轮精彩的系列赛和一个精彩的赛季是我的责任。”\n" +
                "\n" +
                "“正如我所说,我痛恨失败,但你能从失败中学到很多东西。我骄傲于自己的桀骜不屈,但如果那样子离开球场,不去恭喜他们所获得的成就,那我很长一段时间内都会看不起自己。所以,当我静坐片刻之后,我知道最正确的事情就是回到球场,恭喜他们打出一个精彩的赛季,一轮精彩的系列赛,赢得了总冠军。”\n" +
                "\n" +
                "本场比赛,格林登场47分钟,得到了32分15篮板9助攻2抢断。");
        json.put("sex","男");

        IndexResponse response = createIndex(client, json,index, type,valueid);//创建索引

        updateIndex(client,index,type,valueid,"name","詹姆斯");//修改
        System.out.println("create index result:"+response.toString());

//        deleteIndex(client,index, type,valueid);

        GetResponse re = getIndex(client, index, type,valueid);//根据valueid获取索引
        System.out.println("get index result:"+re.getSourceAsString());

        searchIndex(client,index,type,"about","痛恨失败");//查询
    }
}

更多elasticsearch操作详情请参考官方demo

https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/index.html

转载于:https://my.oschina.net/liuxundemo/blog/697914