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

相关文章

Ubuntu 24.04启用root图形登录的操作流程

《Ubuntu24.04启用root图形登录的操作流程》Ubuntu默认禁用root账户的图形与SSH登录,这是为了安全,但在某些场景你可能需要直接用root登录GNOME桌面,本文以Ubuntu2... 目录一、前言二、准备工作三、设置 root 密码四、启用图形界面 root 登录1. 修改 GDM 配

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

MyBatis-Plus通用中等、大量数据分批查询和处理方法

《MyBatis-Plus通用中等、大量数据分批查询和处理方法》文章介绍MyBatis-Plus分页查询处理,通过函数式接口与Lambda表达式实现通用逻辑,方法抽象但功能强大,建议扩展分批处理及流式... 目录函数式接口获取分页数据接口数据处理接口通用逻辑工具类使用方法简单查询自定义查询方法总结函数式接口

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.

JSONArray在Java中的应用操作实例

《JSONArray在Java中的应用操作实例》JSONArray是org.json库用于处理JSON数组的类,可将Java对象(Map/List)转换为JSON格式,提供增删改查等操作,适用于前后端... 目录1. jsONArray定义与功能1.1 JSONArray概念阐释1.1.1 什么是JSONA