首页 > 编程知识 正文

elasticsearch索引和文档,elasticsearch 自动创建索引

时间:2023-05-03 22:06:08 阅读:194425 作者:4142

一、基础概念:

1、索引:

索引(index)是elasticsearch的一个逻辑存储,可以理解为关系型数据库中的数据库,es可以把索引数据存放到一台服务器上,也可以sharding后存到多台服务器上,每个索引有一个或多个分片,每个分片可以有多个副本。

2、索引类型(index_type):

在es中,一个索引对象可以存储多个不同用途的对象,通过索引类型(index_type)可以区分单个索引中的不同对象,可以理解为关系型数据库中的表。每个索引类型可以有不同的结构,但是不同的索引类型不能为相同的属性设置不同的类型。

3、文档(document):

存储在es中的主要实体叫文档(document),可以理解为关系型数据库中表的一行记录。每个文档由多个字段构成,es是一个非结构化的数据库,每个文档可以有不同的字段,并且有一个唯一的标识符。

4、映射(mapping):

ES默认是动态创建索引和索引类型的mapping的。这就相当于无需定义Solr中的Schema,无需指定各个字段的索引规则就可以索引文件,很方便。但有时方便就代表着不灵活。比如,ES默认一个字段是要做分词的,但我们有时要搜索匹配整个字段却不行。如有统计工作要记录每个城市出现的次数。对于NAME字段,若记录“new york”文本,ES可能会把它拆分成“new”和“york”这两个词,分别计算这个两个单词的次数,而不是我们期望的“new york”。

这时,就需要我们在创建索引时定义mapping。此外,es支持多字段结构,例如:我们希望两个字段中有相同的值,一个用于搜索,一个用户排序;或者一个用于分词器分析,一个用于空白字符。例如:编写mapping文件如下:

{ "index_type":{ "properties":{ "ID":{ "type":"string", "index":"not_analyzed" }, "NAME":{"type":"string","fields":{"NAME":{"type":"string"},"raw":{"type":"string","index":"not_analyzed"}} } } } }以上文件是说我们对于index_type这个索引类型,定义了它的mapping。重点是将NAME这个字段映射为两个,一个是需要做索引分析的NAME,另一个是不分析的raw,即不会拆分new york这种词组。这样我们在做搜索的时候,就可以对NAME.raw这个字段做term aggregation,获得所有城市出现的次数了。term aggregation的REST方式的请求编写如下:
{ "query": { "match_all": {} }, "aggregations": { "cityAggs": { "terms": { "field": "NAME.raw" } } }}
二、创建索引:

1、使用postman工具:

1)es提供了restful api,可以通过post请求,创建索引的mapping。如下图:url为es服务器集群中的一个节点ip,端口是9200,其中test是索引名称;post数据中,test_type是索引类型名称,里面包含了两个字段id和name


2)删除索引:

同样,es提供了restful api,可以通过delete请求,删除索引。


2、使用es-java api:

上面我们使用了http常用的方式创建所以,接下来我们使用api的方式:

public static boolean createIndex(String indexName, String indexType,String mappingSource) {if (isExistsIndex(indexName)) {return false;}IndicesAdminClient indicesAdminClient = transportClient.admin().indices();// settingSettings settings = Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 2).build();// mappingCreateIndexResponse response = indicesAdminClient.prepareCreate(indexName).setSettings(settings)// setting.addMapping(indexType, mappingSource)// type,mapping.get();return response.isAcknowledged();}public static void testCreateIndex4Mapping() {String indexName= "test";String indexType = "test_type";JSONObject mappingJson = new JSONObject();JSONObject mappingTypeJson = new JSONObject();JSONObject propertiesJson = new JSONObject();JSONObject idJson = new JSONObject();idJson.put("type", "string");idJson.put("store", "true");propertiesJson.put("id", idJson);JSONObject nameJson = new JSONObject();nameJson.put("type", "string");propertiesJson.put("name", nameJson);mappingTypeJson.put("properties", propertiesJson);mappingJson.put(indexType, mappingTypeJson);logger.info(mappingJson.toJSONString());createIndex(indexName, indexType, mappingJson.toJSONString());}
其中,mappingSource打印出来的字符:

{"test_type": {"properties": {"id": {"store": "true","type": "string"},"name": {"type": "string"}}}}


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。