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

ElasticSearch 增删改查

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

0 概述

本文主要介绍使用java API 对ElasticSearch 的增删改查的操作,以及在增删改查中遇到的问题。
项目依赖pom

<dependencies>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.0.0</version>
        </dependency>
        <!--log4j2 这个是强依赖-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.6.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.6.2</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.29</version>
        </dependency>
    </dependencies>

1 数据写入

数据写入前建议提前创建好索引和mapping,因为提前创建好可以确定该字段的类型和是否需要分词,否则的话ElasticSearch 会自动根据插入的数据自动创建mapping。创建的方法具体可以见:创建索引和mapping

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.rest.RestStatus;

import java.util.Map;

/**
 * Created by hsc on 17/4/29.
 */
public class ElasticSearchOperations {

    private static final Logger logger = LogManager.getLogger(ElasticSearchOperations.class);

    /**
     * @param index   索引 名称
     * @param type    文档类型
     * @param id      文档id(相当于关系数据库表的主键)
     * @param dataMap 数据
     * @return
     */
    public static boolean AddOrUpdate(String index, String type, String id, Map<String, Object> dataMap) {
        try {
            IndexResponse indexRespons = ESClient.getInstance()
                    .prepareIndex(index, type)
                    .setId(id)
                    .setSource(dataMap)
                    .get();
            return isSuccess(indexRespons);
        } catch (Exception ex) {
            logger.error("save or update elasticsearch exception", ex);
        }
        return false;
    }

    private static boolean isSuccess(Object response) {
        if (response instanceof IndexResponse) {
            //返回状态有两种情况-第一:该文档id不存在,进行创建写入RestStatus.CREATED ; 第二,文档id已经存在,进行更新操作返回RestStatus.OK
            return RestStatus.CREATED.equals(((IndexResponse) response).status()) || RestStatus.OK.equals(((IndexResponse) response).status());
        } else if (response instanceof DeleteResponse) {
            return RestStatus.OK.equals(((DeleteResponse) response).status());
        }
        return false;
    }

    public static boolean delete(String index, String type, String id) {
        try {
            DeleteResponse deleteResponse = ESClient.getInstance().prepareDelete(index, type, id).get();
            return isSuccess(deleteResponse);
        } catch (Exception ex) {
            logger.error("delete elasticSearch exception", ex);
        }
        return false;

    }


}

值得强调的是:在数据写入时候,如果不指定文档Id,ES 会自动创建id,相当于关系数据库中自增的主键id。如果插入数据时候该文档Id已经存在,ES则会更新这条记录
Elasticsearch操作数据后马上更新的办法,就是写入数据时候刷新下,具体的写法可以见下面

   IndexResponse indexRespons = ESClient.getInstance()
                    .prepareIndex(index, type)
                    .setId(id)
                    .setSource(dataMap)
                    .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
                    .get();

2数据查询

这里只是给出一个简单的查询方式

import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHits;

/**
 * Created by hsc on 17/4/29.
 */
public class SearchComponent {
    public static SearchHits search(String index, String type) {
        try {
            SearchResponse searchResponse = buildSearchRequestBuilder(index, type, 100).execute().get();
            return searchResponse.getHits();
        } catch (Exception ex) {
            System.out.print("search exception " + ex.getMessage());
        }
        return null;
    }

    private static SearchRequestBuilder  buildSearchRequestBuilder(String index, String type, int size) {
        SearchRequestBuilder searchRequestBuilder = ESClient.getInstance().prepareSearch();
        searchRequestBuilder.setIndices(index)
                .setTypes(type)
                .setSize(size);
        return searchRequestBuilder;
    }
}

测试主类

import com.alibaba.fastjson.JSON;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by hsc on 17/4/29.
 */
public class Test {
    public static void main(String[] args) {
        String index = "index";
        String type = "test";
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("userId", 1213);
        data.put("userName", "hsc");
        ElasticSearchOperations.AddOrUpdate(index, type, "test2", data);
        SearchHits searchHits = SearchComponent.search(index, type);
        if (searchHits != null) {
            System.out.println("总共数据:"+searchHits.getTotalHits());
            for (SearchHit hit : searchHits.getHits()) {
                System.out.println(JSON.toJSON(hit.getSource()));
            }
        }
    }
}
相关标签: elasticsearch