Elasticsearch5.x创建索引(Java)
索引创建代码使用官方给的示例代码,我把它在java项目里实现了一遍。
1、创建索引
/**
* Java创建Index
*/
public void CreateIndex() {
int i = 0;
List<IndexDomain> list = getIndexList(); for (IndexDomain indexDomain : list) {
if (indexExists(indexDomain.getIndex())) {
continue;
} // create indexDomain, setting, put mapping
adminClient.prepareCreate(indexDomain.getIndex())
.setSettings(Settings.builder()
.put("indexDomain.number_of_shards", indexDomain.getNumber_of_shards())
.put("indexDomain.number_of_replicas", indexDomain.getNumber_of_replicas())
)
.addMapping(indexDomain.getType(), indexDomain.getFieldsJson())
.get(); i++;
}
System.out.println("IndexDomain creation success! create " + i + " IndexDomain");
}
2、附一些其它小方法:
2.1 集群初始化
private Client client;
private IndicesAdminClient adminClient; /**
* 构造方法 单例
*/
public Elasticsearch() {
try {
init();
} catch (Exception e) {
System.out.println("init() exception!");
e.printStackTrace();
}
adminClient = client.admin().indices();
} /**
* 集群配置初始化方法
*
* @throws Exception
*/
private void init() throws Exception {
// 读取配置文件中数据
Properties properties = readElasticsearchConfig();
String clusterName = properties.getProperty("clusterName");
String[] inetAddresses = properties.getProperty("hosts").split(","); Settings settings = Settings.builder().put("cluster.name", clusterName).build(); client = new PreBuiltTransportClient(settings); for (int i = 0; i < inetAddresses.length; i++) {
String[] tmpArray = inetAddresses[i].split(":");
String ip = tmpArray[0];
int port = Integer.valueOf(tmpArray[1]); client = ((TransportClient) client).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(ip), port));
}
}
2.2 读取ES配置信息
/**
* 读取ES配置信息
*
* @return
*/
public Properties readElasticsearchConfig() {
Properties properties = new Properties();
try {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("elasticsearch.properties");
properties.load(new InputStreamReader(is, "UTF-8"));
} catch (IOException e) {
System.out.println("readEsConfig exception!");
e.printStackTrace();
}
return properties;
}
elasticsearch.properties
hosts: 192.168.33.5:9300,192.168.33.50:9300
clusterName: my-es-analyze
2.3 读取json配置文件
/**
* 读取json配置文件
*
* @return JSONArray
* @throws IOException
*/
public JSONArray readJosnFile() throws IOException {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("index.json");
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sb = new StringBuffer();
String tmp = null;
while ((tmp = br.readLine()) != null) {
sb.append(tmp);
}
JSONArray result = JSONArray.parseArray(sb.toString());
return result;
}
index.json
[
{
"index": "caixiao",
"type": "compensate",
"number_of_shards": 2,
"number_of_replicas": 1,
"fieldsSource": {
"compensate": {
"properties": {
"name": {
"type": "string"
},
"message": {
"type": "string"
},"createtime": {
"type": "date"
}
}
}
}
}
]
2.4 判断集群中索引是否存在
/**
* 判断集群中{Index}是否存在
*
* @param index
* @return 存在(true)、不存在(false)
*/
public boolean indexExists(String index) {
IndicesExistsRequest request = new IndicesExistsRequest(index);
IndicesExistsResponse response = adminClient.exists(request).actionGet();
if (response.isExists()) {
return true;
}
return false;
}
2.5 创建索引实体类
/**
* 获取要创建的index列表
*
* @return List<IndexDomain>
*/
public List<IndexDomain> getIndexList() { List<IndexDomain> result = new ArrayList<IndexDomain>();
JSONArray jsonArray = null;
try {
jsonArray = readJosnFile();
} catch (IOException e) {
System.out.println("readJsonFile exception!");
e.printStackTrace();
} if (jsonArray == null || jsonArray.size() == 0) {
return null;
} for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
IndexDomain indexDomainObject = new IndexDomain();
String index = jsonObject.getString("index");
String type = jsonObject.getString("type");
Integer number_of_shards = jsonObject.getInteger("number_of_shards");
Integer number_of_replicas = jsonObject.getInteger("number_of_replicas");
String fieldsSource = jsonObject.get("fieldsSource").toString(); indexDomainObject.setIndex(index);
indexDomainObject.setType(type);
indexDomainObject.setFieldsJson(fieldsSource);
indexDomainObject.setNumber_of_shards(number_of_shards);
indexDomainObject.setNumber_of_replicas(number_of_replicas);
result.add(indexDomainObject);
}
return result;
}
2.6 索引实体类
public class IndexDomain {
private String index; //索引名
private String type; //type表名
private Integer number_of_shards; //分片数
private Integer number_of_replicas; //备份数
private String fieldsJson; //字段类型
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFieldsJson() {
return fieldsJson;
}
public void setFieldsJson(String fieldsJson) {
this.fieldsJson = fieldsJson;
}
public Integer getNumber_of_shards() {
return number_of_shards;
}
public void setNumber_of_shards(Integer number_of_shards) {
this.number_of_shards = number_of_shards;
}
public Integer getNumber_of_replicas() {
return number_of_replicas;
}
public void setNumber_of_replicas(Integer number_of_replicas) {
this.number_of_replicas = number_of_replicas;
}
}
2.7 log4j2.properties
appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatternLayout rootLogger.level = info
rootLogger.appenderRef.console.ref = console
2.8 pom文件依赖
<properties>
<elasticsearch.version>5.3.0</elasticsearch.version>
<log4j.version>2.8.2</log4j.version>
<fastjson.version>1.2.31</fastjson.version>
</properties> <dependencies>
<!-- Elasticsearch -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>${elasticsearch.version}</version>
</dependency> <!-- Log4j -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency> <!-- Alibaba Json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
</dependencies>
Elasticsearch5.x创建索引(Java)的更多相关文章
- elasticsearch 5.6.4自动创建索引与mapping映射关系 +Java语言
由于业务上的需求 ,最近在研究elasticsearch的相关知识 ,在网上查略了大部分资料 ,基本上对elasticsearch的数据增删改都没有太大问题 ,这里就不做总结了 .但是,在网上始终没 ...
- [搜索]ElasticSearch Java Api(一) -添加数据创建索引
转载:http://blog.csdn.net/napoay/article/details/51707023 ElasticSearch JAVA API官网文档:https://www.elast ...
- java mongodb 基础系列---查询,排序,limit,$in,$or,输出为list,创建索引,$ne 非操作
官方api教程:http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/#getting-started ...
- ElasticSearch6.0 Java API 使用 排序,分组 ,创建索引,添加索引数据,打分等(一)
ElasticSearch6.0 Java API 使用 排序,分组 ,创建索引,添加索引数据,打分等 如果此文章对你有帮助,请关注一下哦 1.1 搭建maven 工程 创建web工程 ...
- ElasticSearch(java) 创建索引
搜索]ElasticSearch Java Api(一) -创建索引 标签: elasticsearchapijavaes 2016-06-19 23:25 33925人阅读 评论(30) 收藏 举报 ...
- Elastic Search Java Api 创建索引结构,添加索引
创建TCP客户端 Client client = new TransportClient() .addTransportAddress(new InetSocketTransportAddress( ...
- Java High Level REST Client 之 创建索引
1. 创建索引请求 CreateIndexRequest request = new CreateIndexRequest("twitter"); 2.设置 2.1 分别设置 2. ...
- Solr DIH以Mysql为数据源批量创建索引
演示使用solr管理后台,以mysql为数据源,批量建索引的方法 测试于:Solr 4.5.1, mmseg4j 1.9.1, Jdk 1.6.0_45, Tomcat 6.0.37 | CentOS ...
- lucene创建索引简单示例
利用空闲时间写了一个使用lucene创建索引简单示例, 1.使用maven创建的项目 2.需要用到的jar如下: 废话不多说,直接贴代码如下: 1.创建索引的类(HelloLucene): packa ...
随机推荐
- Linux关闭IPV6
Linux关闭IPV6的方法 修改配置文件/etc/sysctl.conf添加以下1行 net.ipv6.conf.all.disable_ipv6 = 1 设置生效 sysctl -p 查看没有IP ...
- 联想y720 淋了雨,字体变得模糊了
显卡驱动没有问题 重新校准显示器问题解决 事实上,可能是某些软件 扰乱了系统字体,请安装上述来重新调整显示器的字体清晰度
- tensorflow模型在实际上线进行预测的时候,使用CPU工作
最近已经训练好了一版基于DeepLearning的文本分类模型,TextCNN原理.在实际的预测中,如果默认模型会优先选择GPU那么每一次实例调用,都会加载GPU信息,这会造成很大的性能降低. 那么, ...
- SQLServer 索引重建
SQL Server 索引重建脚本 在数据的使用过程中,由于索引page碎片过多,带来一些不利的性能问题,我们有时候需要对数据库中的索引进行重组或者重建工作.通常这个阈值为30%,大于30%我们建议进 ...
- spark分组统计及二次排序案例一枚
组织数据形式: aa 11 bb 11 cc 34 aa 22 bb 67 cc 29 aa 36 bb 33 cc 30 aa 42 bb 44 cc 49 需求: 1.对上述数据按key值进行分组 ...
- linux:基本概念和操作
1. 终端 Linux 默认提供了 6 个纯命令行界面的 “terminal”(准确的说这里应该是 6 个 virtual consoles)来让用户登录,在物理机系统上你可以通过使用[Ctrl]+[ ...
- Usage of git
目录 Git 配置 查看配置信息 基本概念 Git 创建仓库 git init git clone 撤销操作 从暂存区恢复文件 从仓库恢复某个文件 版本退回 版本前进 分支操作 删除未跟踪的文件 连 ...
- 转:JAVA 的wait(), notify()与synchronized同步机制
原文地址:http://blog.csdn.net/zyplus/article/details/6672775 转自:https://www.cnblogs.com/x_wukong/p/40097 ...
- 树和二叉树->线索二叉树
文字描述 从二叉树的遍历可知,遍历二叉树的输出结果可看成一个线性队列,使得每个结点(除第一个和最后一个外)在这个线形队列中有且仅有一个前驱和一个后继.但是当采用二叉链表作为二叉树的存储结构时,只能得到 ...
- Excel--数据分列功能
原文:http://www.ittribalwo.com/article/3963.html excel分列功能一:按照固定宽度进行数据拆分 情景: 如下图所示,在日常工作中,我们经常需要根据人员的身 ...