// 示例:创建电商商品索引的映射(Java API)
public class IndexMappingExample {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
// 创建索引并定义映射
CreateIndexRequest request = new CreateIndexRequest("ecommerce_products");
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject()
.startObject("mappings")
.startObject("properties")
// 文本类型:全文搜索
.startObject("product_name")
.field("type", "text")
.field("analyzer", "ik_max_word") // 中文分词
.endObject()
// 关键字类型:精确匹配
.startObject("product_id")
.field("type", "keyword")
.field("ignore_above", 50) // 长度超过50不索引
.endObject()
// 数值类型:价格优化
.startObject("price")
.field("type", "scaled_float") // 用scaled_float节省存储
.field("scaling_factor", 100) // 小数点后两位
.endObject()
// 时间类型:自动解析
.startObject("created_at")
.field("type", "date")
.field("format", "yyyy-MM-dd HH:mm:ss||epoch_millis")
.endObject()
.endObject()
.endObject()
.endObject();
request.mapping(builder);
client.indices().create(request, RequestOptions.DEFAULT);
client.close();
}
}
注释说明:
ik_max_word
分词器支持中文全文搜索。ignore_above
避免大字段索引,节省存储。// 示例:动态映射自动选择类型(ES的“量子叠加态”)
PUT /auto_mapping_test
POST /auto_mapping_test/_doc
{
"title": "量子计算入门", // 自动识别为text
"category": "量子物理", // 自动识别为keyword
"price": 2999.00, // 自动识别为float
"is_available": true, // 自动识别为boolean
"tags": ["AI", "量子计算"] // 自动识别为keyword数组
}
注释说明:
// 示例:价格字段优化(Java API)
XContentBuilder priceField = XContentFactory.jsonBuilder()
.startObject("price")
.field("type", "scaled_float")
.field("scaling_factor", 100) // 小数点后两位
.endObject();
// 转换逻辑:3999.00元存储为399900整数
// 查询时自动还原:399900 / 100 = 3999.00
注释说明:
// 示例:电商商品索引的“量子纠缠态”配置
PUT /ecommerce_products
{
"mappings": {
"properties": {
"product_name": {
"type": "text",
"analyzer": "ik_smart", // 中文智能分词
"fielddata": true // 启用聚合支持(需权衡内存)
},
"sku": {
"type": "keyword",
"eager_global_ordinals": true // 预加载全局序数加速聚合
},
"category": {
"type": "keyword",
"normalizer": "lowercase" // 统一转小写
},
"tags": {
"type": "keyword",
"copy_to": "all_tags" // 复制到其他字段
},
"specs": {
"type": "object",
"properties": { // 嵌套对象
"color": { "type": "keyword" },
"size": { "type": "keyword" }
}
}
}
}
}
注释说明:
// 示例:电商商品索引的“量子纠缠态”配置
PUT /ecommerce_products_v2
{
"settings": {
"number_of_shards": 5, // 分片数量(根据数据量调整)
"number_of_replicas": 1 // 副本数量(高可用性)
},
"mappings": {
"properties": {
"product_name": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart" // 搜索时用更智能的分词
},
"price": {
"type": "scaled_float",
"scaling_factor": 100
},
"category_path": {
"type": "keyword",
"index": "false" // 不索引,仅存储
},
"specs": {
"type": "object",
"properties": {
"color": {
"type": "keyword",
"eager_global_ordinals": true
},
"weight": {
"type": "integer" // 单位:克
}
}
},
"created_at": {
"type": "date"
}
}
}
}
注释说明:
ik_max_word
索引更多分词,ik_smart
搜索时更智能。index: false
仅存储不索引,节省空间。eager_global_ordinals
加速颜色聚合。// 示例:日志索引的“量子折叠”配置
PUT /logs_2024
{
"mappings": {
"properties": {
"log_level": {
"type": "keyword",
"normalizer": "lowercase" // 统一小写
},
"timestamp": {
"type": "date",
"format": "epoch_millis"
},
"message": {
"type": "text",
"analyzer": "standard",
"store": true // 存储原始日志内容
},
"request_id": {
"type": "keyword",
"ignore_above": 50 // 长ID不索引
},
"user_agent": {
"type": "text",
"analyzer": "uax_url_email" // 优化URL和邮箱解析
}
}
},
"settings": {
"codec": "best_compression" // 压缩存储
}
}
注释说明:
store: true
保留原始日志内容。best_compression
减少存储空间(适合冷数据)。uax_url_email
优化URL和邮箱的分词。// 示例:商品颜色聚合(Java API)
SearchRequest searchRequest = new SearchRequest("ecommerce_products");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.aggregation(
AggregationBuilders.terms("color_agg")
.field("specs.color")
.size(10) // 限制返回项数
.order(BucketOrder.count(false)) // 按计数降序
);
// 量子优化:利用eager_global_ordinals加速
sourceBuilder.size(0); // 不返回文档,仅聚合
searchRequest.source(sourceBuilder);
注释说明:
// 示例:避免使用from+size的“量子隧穿”分页
GET /ecommerce_products/_search
{
"query": { "match_all": {} },
"size": 10,
"search_after": [1620000000000] // 上次最后文档的排序值
}
注释说明:
// 示例:监控索引健康状态(Java API)
public class ClusterMonitor {
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200))
);
// 获取集群状态
ClusterHealthResponse health = client.cluster()
.health(new ClusterHealthRequest(), RequestOptions.DEFAULT);
System.out.println("Status: " + health.getStatus());
// 获取索引统计信息
IndicesStatsResponse stats = client.indices()
.stats(new IndicesStatsRequest("ecommerce_products"), RequestOptions.DEFAULT);
System.out.println("Doc Count: " + stats.getTotal().getDocs().getCount());
client.close();
}
}
注释说明: