elasticsearch__1__java操作之连接es,创建Mapping,保存数据

2024-06-03 13:58

本文主要是介绍elasticsearch__1__java操作之连接es,创建Mapping,保存数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


elasticsearch 分布式搜索系列专栏:http://blog.csdn.net/xiaohulunb/article/category/2399789

内容涉及代码GitHub地址: 点击打开链接



官方API:http://www.elasticsearch.org/guide/en/elasticsearch/client/java-api/current/index.html



操作demo所用javabean


package com.elasticsearch;import com.google.common.collect.Lists;
import com.util.date.Joda_Time;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;import java.io.IOException;
import java.util.Date;
import java.util.List;/*** Created by lw on 14-7-8.*/
public class User {private String name;private String home;//家乡private double height;//身高private int age;private Date birthday;public User() {}public User(String name, String home, double height, int age, Date birthday) {this.name = name;this.home = home;this.height = height;this.age = age;this.birthday = birthday;}/*** 随机生成一个用户信息** @return*/public static User getOneRandomUser() {return new User("葫芦" + (int) (Math.random() * 1000) + "娃", "山西省太原市" + (int) (Math.random() * 1000) + "街道", (Math.random() * 1000), (int) (Math.random() * 100), new Date(System.currentTimeMillis() - (long) (Math.random() * 100000)));}/*** 随机生成num个用户信息** @param num 生成数量* @return*/public static List<User> getRandomUsers(int num) {List<User> users = Lists.newArrayList();if (num < 0) num = 10;for (int i = 0; i < num; i++) {users.add(new User("葫芦" + (int) (Math.random() * 1000) + "娃", "山西省太原市" + (int) (Math.random() * 1000) + "街道", (Math.random() * 1000), (int) (Math.random() * 100), new Date(System.currentTimeMillis() - (long) (Math.random() * 100000))));}return users;}/*** 封装对象的Json信息** @param user* @return* @throws IOException*/public static XContentBuilder getXContentBuilder(User user) throws IOException {return XContentFactory.jsonBuilder().startObject().field("name", user.getName())//该字段在上面的方法中mapping定义了,所以该字段就有了自定义的属性,比如 age等.field("home", user.getHome()).field("height", user.getHeight()).field("age", user.getAge()).field("birthday", user.getBirthday()).field("state", "默认属性,mapping中没有定义")//该字段在上面方法中的mapping中没有定义,所以该字段的属性使用es默认的..endObject();}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getHome() {return home;}public void setHome(String home) {this.home = home;}public double getHeight() {return height;}public void setHeight(double height) {this.height = height;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}}



java与elasticsearch的交互demo

package com.framework_technology.elasticsearch;import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequestBuilder;
import org.elasticsearch.action.admin.indices.alias.exists.AliasesExistRequestBuilder;
import org.elasticsearch.action.admin.indices.alias.exists.AliasesExistResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.stats.IndexStats;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** Created by lw on 14-7-7.* <p>* mapping创建* 添加记录到es*/
public class Es_BuildIndex {/*** 索引的mapping* <p>* 预定义一个索引的mapping,使用mapping的好处是可以个性的设置某个字段等的属性* Es_Setting.INDEX_DEMO_01类似于数据库* mapping 类似于预设某个表的字段类型* <p>* Mapping,就是对索引库中索引的字段名及其数据类型进行定义,类似于关系数据库中表建立时要定义字段名及其数据类型那样,* 不过es的 mapping比数据库灵活很多,它可以动态添加字段。* 一般不需要要指定mapping都可以,因为es会自动根据数据格式定义它的类型,* 如果你需要对某 些字段添加特殊属性(如:定义使用其它分词器、是否分词、是否存储等),就必须手动添加mapping。* 有两种添加mapping的方法,一种是定义在配 置文件中,一种是运行时手动提交mapping,两种选一种就行了。** @throws Exception Exception*/protected static void buildIndexMapping() throws Exception {Map<String, Object> settings = new HashMap<>();settings.put("number_of_shards", 4);//分片数量settings.put("number_of_replicas", 0);//复制数量settings.put("refresh_interval", "10s");//刷新时间//在本例中主要得注意,ttl及timestamp如何用java ,这些字段的具体含义,请去到es官网查看CreateIndexRequestBuilder cib = Es_Utils.client.admin().indices().prepareCreate(Es_Utils.LOGSTASH_YYYY_MM_DD);cib.setSettings(settings);XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("we3r")//.startObject("_ttl")//有了这个设置,就等于在这个给索引的记录增加了失效时间,//ttl的使用地方如在分布式下,web系统用户登录状态的维护..field("enabled", true)//默认的false的.field("default", "5m")//默认的失效时间,d/h/m/s 即天/小时/分钟/秒.field("store", "yes").field("index", "not_analyzed").endObject().startObject("_timestamp")//这个字段为时间戳字段.即你添加一条索引记录后,自动给该记录增加个时间字段(记录的创建时间),搜索中可以直接搜索该字段..field("enabled", true).field("store", "no").field("index", "not_analyzed").endObject()//properties下定义的name等等就是属于我们需要的自定义字段了,相当于数据库中的表字段 ,此处相当于创建数据库表.startObject("properties").startObject("@timestamp").field("type", "long").endObject().startObject("name").field("type", "string").field("store", "yes").endObject().startObject("home").field("type", "string").field("index", "not_analyzed").endObject().startObject("now_home").field("type", "string").field("index", "not_analyzed").endObject().startObject("height").field("type", "double").endObject().startObject("age").field("type", "integer").endObject().startObject("birthday").field("type", "date").field("format", "YYYY-MM-dd").endObject().startObject("isRealMen").field("type", "boolean").endObject().startObject("location").field("lat", "double").field("lon", "double").endObject().endObject().endObject().endObject();cib.addMapping(Es_Utils.LOGSTASH_YYYY_MM_DD_MAPPING, mapping);cib.execute().actionGet();}/*** 给 []index 创建别名* 重载方法可以按照过滤器或者Query 作为一个别名** @param aliases aliases别名* @param indices 多个 index* @return 是否完成*/protected static boolean createAliases(String aliases, String... indices) {IndicesAliasesRequestBuilder builder = Es_Utils.client.admin().indices().prepareAliases();return builder.addAlias(indices, aliases).execute().isDone();}/*** 查询此别名是否存在** @param aliases aliases* @return 是否存在*/protected static boolean aliasesExist(String... aliases) {AliasesExistRequestBuilder builder =Es_Utils.client.admin().indices().prepareAliasesExist(aliases);AliasesExistResponse response = builder.execute().actionGet();return response.isExists();}/*** 添加记录到es* <p>* 增加索引记录** @param user 添加的记录* @throws Exception Exception*/protected static void buildIndex(User user) throws Exception {// INDEX_DEMO_01_MAPPING为上个方法中定义的索引,prindextype为类型.jk8231为id,以此可以代替memchche来进行数据的缓存IndexResponse response = Es_Utils.client.prepareIndex(Es_Utils.LOGSTASH_YYYY_MM_DD, Es_Utils.LOGSTASH_YYYY_MM_DD_MAPPING).setSource(User.getXContentBuilder(user)).setTTL(8000)//这样就等于单独设定了该条记录的失效时间,单位是毫秒,必须在mapping中打开_ttl的设置开关.execute().actionGet();}/*** 批量添加记录到索引** @param userList 批量添加数据* @throws java.io.IOException IOException*/protected static void buildBulkIndex(List<User> userList) throws IOException {BulkRequestBuilder bulkRequest = Es_Utils.client.prepareBulk();// either use Es_Setting.client#prepare, or use Requests# to directly build index/delete requestsfor (User user : userList) {//通过add批量添加bulkRequest.add(Es_Utils.client.prepareIndex(Es_Utils.LOGSTASH_YYYY_MM_DD, Es_Utils.LOGSTASH_YYYY_MM_DD_MAPPING).setSource(User.getXContentBuilder(user)));}BulkResponse bulkResponse = bulkRequest.execute().actionGet();//如果失败if (bulkResponse.hasFailures()) {// process failures by iterating through each bulk response itemSystem.out.println("buildFailureMessage:" + bulkResponse.buildFailureMessage());}}}


数据查看










这篇关于elasticsearch__1__java操作之连接es,创建Mapping,保存数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1027183

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

PHP轻松处理千万行数据的方法详解

《PHP轻松处理千万行数据的方法详解》说到处理大数据集,PHP通常不是第一个想到的语言,但如果你曾经需要处理数百万行数据而不让服务器崩溃或内存耗尽,你就会知道PHP用对了工具有多强大,下面小编就... 目录问题的本质php 中的数据流处理:为什么必不可少生成器:内存高效的迭代方式流量控制:避免系统过载一次性

Python正则表达式匹配和替换的操作指南

《Python正则表达式匹配和替换的操作指南》正则表达式是处理文本的强大工具,Python通过re模块提供了完整的正则表达式功能,本文将通过代码示例详细介绍Python中的正则匹配和替换操作,需要的朋... 目录基础语法导入re模块基本元字符常用匹配方法1. re.match() - 从字符串开头匹配2.

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——