ElasticSearch—— Java API

本文详细介绍如何在本地环境中安装并配置Elasticsearch 6.4.0,包括环境准备、单机版启动、Head插件安装及使用,以及通过JestClient进行增删改查操作。同时,深入探讨了如何利用RESTClient进行索引管理,包括创建、删除索引,添加、删除文档,以及复杂的检索操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实战

在了解了ES的基础知识后,接下来就是实际操作了。

安装

环境准备:
jdk 1.8
ElasticSearch 6.4.0
window7

步骤:

  1. 将下载下来的elasticsearch-6.4.0.zip 解压
  2. 进入/bin目录,直接在terminal窗口中运行elasticsearch.bat 命令,然后就可以看到如下启动页面;

此时在浏览器中访问http://localhost:9200 ;

在启动过程中默认的jvm内存参数设置比较大,可以在config目录下面的jvm.options中将-Xms和-Xmx调小

至此表示单机版的ES已经成功启动。

  1. 安装head插件(用来查看ES集群中的数据和健康信息)
git clone git://github.com/mobz/elasticsearch-head.git
cd elasticsearch-head
npm install
npm run start
复制代码

启动后,可以在浏览器中访问9100端口

至此headr安装成功,可以在页面上查看整个集群的信息。

通过上述的几个步骤,我们就成功的搭建了一个可以试验的ES环境,使用header插件可以更加方便的查看ES中索引,分片和文档的信息。

由于存在跨域问题,所以需要在elasticsearch目录中config下的elasticsearch.yml文件中添加

http.cors.enabled: true
http.cors.allow-origin: "*"
复制代码

Java 客户端

ES是基于http和json来和客户端交互的,因此官方也提供了一个RESTClient客户端,所以我们也借助这个client来实现增删改查的操作。

依赖:

org.elasticsearch:elasticsearch:5.4.2 ->ES 平台版本
org.elasticsearch.client:rest:5.4.2 -> restClient 版本
io.searchbox:jest:5.3.3 -> 基于RestClient的一个封装

复制代码
  1. 初始化Client

在使用jest时,会创建一个全局单例的JestClient,然后在整个应用的生命周期中都会使用该client

JestClientFactory factory = new JestClientFactory();
List<String> urls = new ArrayList<>();
//        urls.add("http://10.37.2.142:9900");
urls.add("http://127.0.0.1:9200");
//        urls.add("http://10.37.2.144:9900");
factory.setHttpClientConfig(new HttpClientConfig
                .Builder(urls)//集群中所有的节点地址
                .multiThreaded(true)//是否使用多线程
                .defaultMaxTotalConnectionPerRoute(2)//每个路由最大连接数
                .maxTotalConnection(20)//整个应用最大的连接数
                .readTimeout(30000)//超时时间
                        .build());
JestClient client = factory.getObject();
复制代码

在应用中可以通过spring对client进行管理,在应用关闭时需要调用client.shutdownClient();将资源进行释放

  1. 创建index
Settings.Builder settingsBuilder = Settings.builder();
settingsBuilder.put("number_of_shards",5);//主分片数
settingsBuilder.put("number_of_replicas",1);//副本数

jestClient.execute(new CreateIndex.Builder("index").settings(settingsBuilder.build().getAsMap()).build());

//创建映射-mapping
PutMapping putMapping = new PutMapping.Builder(
        "my_index",
        "my_type",
        "{ \"my_type\" : { \"properties\" : { \"message\" : {\"type\" : \"string\", \"store\" : \"yes\"} } } }"
).build();
client.execute(putMapping);
复制代码

ES默认是允许动态创建的,所以在创建index时可以不用创建类型的mapping,然后存储document时会动态的创建mapping,查询index下所有类型的mapping

GET 127.0.0.1:9200/db1/_mapping

  1. 删除index

    jestClient.execute(new DeleteIndex.Builder(index)
                    .build());
    复制代码
  2. 增加document

    document的增加是比较简单的

    String source = "{\"user\":\"kimchy\"}";//使用接送字符串
    String source = jsonBuilder()
                    .startObject()
                    .field("user", "kimchy")
                    .field("postDate", "date")
                    .field("message", "trying out Elastic Search")
                    .endObject().string();//使用构造的json
    Map<String, String> source = new LinkedHashMap<String,String>();//使用map
    source.put("user", "kimchy");
    Article source = new Article();//使用pojo对象
    source.setAuthor("John Ronald Reuel Tolkien");
    source.setContent("The Lord of the Rings is an epic high fantasy novel");
    
    Index index = new Index.Builder(source)
                            .index("twitter")//指定index
                            .type("tweet")//指定type
                            .id("1")//指定id,可以不指定则ES自动生成id
                            .build();
    jestClient.execute(index);
    复制代码

    以上是单个增加,我们同样可以使用Bulk批量的插入ES:

    List<Index> indexList = new ArrayList<>();
    for (OrderDto t : datas) {
                Index indexDoc = new Index.Builder(t).index(index).type(type).build();
                indexList.add(indexDoc);
                Bulk.Builder bulkBuilder = new Bulk.Builder();
                bulkBuilder.addAction(indexList);
                BulkResult br = jestClient.execute(bulkBuilder.build());
    }
    
    复制代码
  3. 删除document

每个document都是由index,type,id三者共同唯一确定的,所以可以指定删除某个document:

jestClient.execute(new Delete.Builder("1")//id =1
        .index("index")//  index = index
        .type("type")// type = type
        .build());
复制代码

同样的我们可以根据条件进行删除:

String query ="\"{\n"+
                    "\"query\": {\n"+
                "\"match_all\": {}\n"+
            "}\"";//查询条件
DeleteByQuery deleteByQuery = new DeleteByQuery.Builder(query).build();
JestResult deleteResult = jestClient.execute(deleteByQuery);
复制代码

如上,表示删除所有的document,查询的条件后面会介绍。

  1. 检索

一切都是为了检索
检索才是ES的最诱人的特性,首先先简单感受一下

    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    TermQueryBuilder memberTerm = QueryBuilders.termQuery("memberId", memberId);//等值查询
    Integer[] channels = {101, 106};
    TermsQueryBuilder orderChannelTerm = QueryBuilders.termsQuery("orderChannel", channels);//in查询
    Integer[] activeType = {0, 8, 9, 7};
    TermsQueryBuilder activeTypeTerm = QueryBuilders.termsQuery("activeType", activeType);
    AggregationBuilder orderItemIdAgg =    .field("b2corditemid").size(Integer.MAX_VALUE);
    Date now = new Date();
    Calendar calendar = Calendar.getInstance(); //得到日历
    calendar.setTime(now);//把当前时间赋给日历
    calendar.add(calendar.MONTH, -3); //设置为前3月
    Date dBefore = calendar.getTime(); //得到前3月的时间
    RangeQueryBuilder payTimeRange = QueryBuilders.rangeQuery("payTime").gt(dBefore).lt(now);//范围查询

    searchSourceBuilder.query(QueryBuilders.boolQuery()
        .must(memberTerm)// and查询
        .filter(orderChannelTerm)//
        .filter(activeTypeTerm)
        .filter(payTimeRange)
        );
    Sort placeTimeSort = new Sort("placeTime", Sort.Sorting.DESC);
    Sort idSort = new Sort("orderId", Sort.Sorting.ASC);
    searchSourceBuilder.aggregation(orderItemIdAgg);// group by 分组
    searchSourceBuilder.from(0).size(20);
    Search search = new Search.Builder(searchSourceBuilder.toString())
                    .addType(type)
                    .addIndex(index)
                    .addSort(placeTimeSort)//结果排序
                    .addSort(idSort)
                    .build();
复制代码

如上的查询可以类似于sql:

SELECT
	*
FROM
	bm_client_order_detail o
WHERE
	o.`payTime` >= DATE_SUB(NOW(), INTERVAL 3 MONTH)
AND o.memberId = 101204389
AND o.orderChannel IN (101, 106)
AND activeType IN (0, 8, 9, 17)
GROUP BY
	o.b2corditemid
ORDER BY
	o.placeTime DESC,
	o.id ASC
LIMIT 0,20
复制代码

重点回顾

  • 单机版ES的安装
  • elasticsearch-header的安装和使用
  • JestClient的使用
    1. 初始化
    2. index创建
    3. index删除
    4. 增加document
    5. 删除document
    6. 检索document

未完待续!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值