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

相关文章

通过ibd文件恢复MySql数据的操作方法

《通过ibd文件恢复MySql数据的操作方法》文章介绍通过.ibd文件恢复MySQL数据的过程,包括知道表结构和不知道表结构两种情况,对于知道表结构的情况,可以直接将.ibd文件复制到新的数据库目录并... 目录第一种情况:知道表结构第二种情况:不知道表结构总结今天干了一件大事,安装1Panel导致原来服务

Java实现将byte[]转换为File对象

《Java实现将byte[]转换为File对象》这篇文章将通过一个简单的例子为大家演示Java如何实现byte[]转换为File对象,并将其上传到外部服务器,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言1. 问题背景2. 环境准备3. 实现步骤3.1 从 URL 获取图片字节数据3.2 将字节数组

Java捕获ThreadPoolExecutor内部线程异常的四种方法

《Java捕获ThreadPoolExecutor内部线程异常的四种方法》这篇文章主要为大家详细介绍了Java捕获ThreadPoolExecutor内部线程异常的四种方法,文中的示例代码讲解详细,感... 目录方案 1方案 2方案 3方案 4结论方案 1使用 execute + try-catch 记录

Jmeter如何向数据库批量插入数据

《Jmeter如何向数据库批量插入数据》:本文主要介绍Jmeter如何向数据库批量插入数据方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Jmeter向数据库批量插入数据Jmeter向mysql数据库中插入数据的入门操作接下来做一下各个元件的配置总结Jmete

SpringBoot接收JSON类型的参数方式

《SpringBoot接收JSON类型的参数方式》:本文主要介绍SpringBoot接收JSON类型的参数方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、jsON二、代码准备三、Apifox操作总结一、JSON在学习前端技术时,我们有讲到过JSON,而在

Spring-AOP-ProceedingJoinPoint的使用详解

《Spring-AOP-ProceedingJoinPoint的使用详解》:本文主要介绍Spring-AOP-ProceedingJoinPoint的使用方式,具有很好的参考价值,希望对大家有所帮... 目录ProceedingJoinPoijsnt简介获取环绕通知方法的相关信息1.proceed()2.g

Spring Security注解方式权限控制过程

《SpringSecurity注解方式权限控制过程》:本文主要介绍SpringSecurity注解方式权限控制过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、摘要二、实现步骤2.1 在配置类中添加权限注解的支持2.2 创建Controller类2.3 Us

Spring MVC跨域问题及解决

《SpringMVC跨域问题及解决》:本文主要介绍SpringMVC跨域问题及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录跨域问题不同的域同源策略解决方法1.CORS2.jsONP3.局部解决方案4.全局解决方法总结跨域问题不同的域协议、域名、端口

SpringBoot项目启动错误:找不到或无法加载主类的几种解决方法

《SpringBoot项目启动错误:找不到或无法加载主类的几种解决方法》本文主要介绍了SpringBoot项目启动错误:找不到或无法加载主类的几种解决方法,具有一定的参考价值,感兴趣的可以了解一下... 目录方法1:更改IDE配置方法2:在Eclipse中清理项目方法3:使用Maven命令行在开发Sprin

JAVA SE包装类和泛型详细介绍及说明方法

《JAVASE包装类和泛型详细介绍及说明方法》:本文主要介绍JAVASE包装类和泛型的相关资料,包括基本数据类型与包装类的对应关系,以及装箱和拆箱的概念,并重点讲解了自动装箱和自动拆箱的机制,文... 目录1. 包装类1.1 基本数据类型和对应的包装类1.2 装箱和拆箱1.3 自动装箱和自动拆箱2. 泛型2