es-字段类型详解

news2025/4/9 6:18:10
  • 字段类型用途示例
    Text全文搜索的字符串字段。json { "type": "text" }
    Keyword精确匹配的字符串字段。json { "type": "keyword" }
    Numeric数值字段(如 integerlongfloat 等)。json { "type": "integer" }
    Date日期和时间字段。json { "type": "date" }
    Boolean布尔值字段。json { "type": "boolean" }
    ObjectJSON 对象字段。json { "type": "object" }
    NestedJSON 对象数组字段。json { "type": "nested" }
    Geo-point经纬度坐标字段。json { "type": "geo_point" }
    IPIP 地址字段。json { "type": "ip" }
    Completion自动补全字段。json { "type": "completion" }
    Runtime Fields动态计算字段值。json { "type": "runtime" }

字段类型详解

1.Text

特点:用于全文搜索的字符串类型,会被分词,支持模糊搜索

使用案例:存储文章内容、产品描述等。

创建Mapping

PUT /my_index
{
  "mappings": {
    "properties": {
      "content": {
        "type": "text"
      }
    }
  }
}

插入数据

POST /my_index/_doc/1
{
  "content": "This is a sample text for Elasticsearch."
}

查找数据

GET /my_index/_search
{
  "query": {
    "match": {
      "content": "sample text"
    }
  }
}

2. Keyword

特点:用于精确匹配的字符串类型,不会被分词,适合存储ID、标签;适合精确查询、聚合和排序

使用案例:存储用户ID、产品SKU、标签等。

创建Mapping

PUT /my_index   
{
   "mappings": {
    "properties": {
      "tag": {
        "type": "keyword"
      }
      }
      }      
}      

插入数据

POST /my_index/_doc/1   
{
   "tag": "elasticsearch"   
}   

查找数据

GET /my_index/_search
{
  "query": {
    "term": {
      "tag": "elasticsearch"
    }
  }
}

tag本身就是


3. Numeric

特点:包括longintegershortbytedoublefloat等,用于存储数值数据。

使用案例

  • long:存储大整数,如用户ID。
  • float,double:存储带小数的数值,如价格、评分。

创建Mapping

PUT /my_index   
{
   "mappings": {
    "properties": {
      "age": {
        "type": "integer"
      }
    }
  }
}

插入数据

POST /my_index/_doc/1
{
  "age": 25   
}   

查找数据

GET /my_index/_search   
{
   "query": {
    "range": {
      "age": {
        "gte": 20,
        "lte": 30
        }
        }
        }        
}           

4. Date

特点:用于存储日期和时间,支持多种日期格式。

使用案例:存储订单日期、日志时间戳等。

创建Mapping

PUT /my_index   
{
   "mappings": {
    "properties": {
      "timestamp": {
        "type": "date"
      }
      }
      }      
}      

插入数据

POST /my_index/_doc/1      
{
      "timestamp": "2023-10-01T12:00:00Z"      
}      

查找数据

GET /my_index/_search      
{
  "query": {
    "range": {
      "timestamp": {
        "gte": "2023-10-01T00:00:00Z",
        "lte": "2023-10-01T23:59:59Z"
        }
        }
        }        
}        

5. Boolean

特点:用于存储布尔值(truefalse)。

使用案例:存储是否已付款、是否激活等。

创建Mapping

PUT /my_index   
{
   "mappings": {
    "properties": {
      "is_active": {
        "type": "boolean"
      }
    }
   }   
}   

插入数据

POST /my_index/_doc/1   
{
   "is_active": true   
}      

查找数据

GET /my_index/_search   
{
   "query": {
    "term": {
      "is_active": true
    }
   }   
}   

6. Object

特点:用于存储JSON对象。

  1. 扁平化存储:Object 类型会将嵌套对象的字段"扁平化"存储到父文档中
  2. 无独立性:数组中的对象不会保持独立关系,会被合并处理
  3. 简单查询:查询语法比 Nested 类型简单,性能更好

使用案例:存储嵌套的用户信息,如用户地址(不需要独立查询子对象)。

创建Mapping

订单mapping,含有物品列表、买家、卖家信息

PUT /object_orders   
{
   "mappings": {
    "properties": {
      "order_id": {
        "type": "keyword"
      },
      "order_date": {
        "type": "date"
      },
      "total_amount": {
        "type": "double"
      },
      "status": {
        "type": "keyword"
      },
      "payment_method": {
        "type": "keyword"
      },
      "items": {
        "type": "object",
        "properties": {
          "product_id": {
            "type": "keyword"
          },
          "product_name": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword"
              }
            }
          },
          "quantity": {
            "type": "integer"
          },
          "price": {
            "type": "double"
          },
          "category": {
            "type": "keyword"
          }
        }
      },
      "buyer": {
        "type": "object",
        "properties": {
          "user_id": {
            "type": "keyword"
          },
          "name": {
            "type": "text"
          },
          "email": {
            "type": "keyword"
          },
          "shipping_address": {
            "type": "text"
          }
        }
      },
      "seller": {
        "type": "object",
        "properties": {
          "seller_id": {
            "type": "keyword"
          },
          "name": {
            "type": "text"
          },
          "rating": {
            "type": "float"
          }
        }
      }
    }
   }   
}

插入数据

POST /object_orders/_doc/1   
{
   "order_id": "ORD-2023-002",
   "order_date": "2023-10-16T14:45:00Z",
   "total_amount": 89.98,
   "status": "processing",
   "payment_method": "paypal",
   "items": [
    {
      "product_id": "P-1003",
      "product_name": "Bluetooth Speaker",
      "quantity": 1,
      "price": 59.99,
      "category": "electronics"
    },
    {
      "product_id": "P-3001",
      "product_name": "Screen Protector",
      "quantity": 1,
      "price": 29.99,
      "category": "accessories"
    }
   ],
   "buyer": {
    "user_id": "U-10002",
    "name": "Alice Johnson",
    "email": "alice.j@example.com",
    "shipping_address": "456 Oak Ave, Los Angeles, CA 90001"
   },
   "seller": {
    "seller_id": "S-5002",
    "name": "GadgetWorld",
    "rating": 4.5
  }
}

查找数据

GET /object_orders/_search   
{
   "query": {
    "term": {
      "status": "processing"
    }
  }   
}   

Object 类型的局限性

  1. 数组对象关系丢失当 items 是对象数组时,数组中的对象会失去彼此间的边界
  2. 交叉匹配问题无法支持查询product_name是Bluetooth,同时price是29 
  3. 无法单独查询:不能单独查询数组中的某个特定对象

何时选择 Object 类型

  1. 当子对象不需要保持独立关系时
  2. 当查询性能比关系精确性更重要时
  3. 当数据结构简单,不需要复杂查询时
  4. 当数据中的数组通常只包含单个对象时

交叉匹配问题case:

一条订单数据有2个商品:

    {
      "product_name": "Bluetooth Speaker",
      "price": 59.99
    },
    {
      "product_name": "Screen Protector",
      "price": 29.99
    }

搜索 Bluetooth Speaker   and 29.99,该订单会被搜索出来(如果需要精准搜索,需要使用nested类型)


7. Nested

特点:用于存储数组中的JSON对象,每个嵌套对象是独立的,支持单独查询

使用案例:订单中的商品列表、用户地址列表等。

创建Mapping

订单的mapping,含有订单信息,订单中的物品信息、买家信息、卖家信息

PUT /orders   
{
   "mappings": {
    "properties": {
      "order_id": {
        "type": "keyword"
      },
      "order_date": {
        "type": "date"
      },
      "total_amount": {
        "type": "double"
      },
      "status": {
        "type": "keyword"
      },
      "payment_method": {
        "type": "keyword"
      },
      "items": {
        "type": "nested",
        "properties": {
          "product_id": {
            "type": "keyword"
          },
          "product_name": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword"
              }
            }
          },
          "quantity": {
            "type": "integer"
          },
          "price": {
            "type": "double"
          },
          "category": {
            "type": "keyword"
          }
        }
      },
      "buyer": {
        "type": "nested",
        "properties": {
          "user_id": {
            "type": "keyword"
          },
          "name": {
            "type": "text"
          },
          "email": {
            "type": "keyword"
          },
          "shipping_address": {
            "type": "text"
          }
        }
      },
      "seller": {
        "type": "nested",
        "properties": {
          "seller_id": {
            "type": "keyword"
          },
          "name": {
            "type": "text"
          },
          "rating": {
            "type": "float"
          }
        }
      }
    }
   }   
}

插入数据

POST /orders/_doc/1   
{
   "order_id": "ORD-2023-001",
   "order_date": "2023-10-15T10:30:00Z",
   "total_amount": 125.99,
   "status": "completed",
   "payment_method": "credit_card",
   "items": [
    {
      "product_id": "P-1001",
      "product_name": "Wireless Headphones",
      "quantity": 1,
      "price": 99.99,
      "category": "electronics"
    },
    {
      "product_id": "P-2002",
      "product_name": "USB-C Cable",
      "quantity": 2,
      "price": 13.00,
      "category": "accessories"
    }
   ],
   "buyer": {
    "user_id": "U-10001",
    "name": "John Smith",
    "email": "john.smith@example.com",
    "shipping_address": "123 Main St, New York, NY 10001"
   },
   "seller": {
    "seller_id": "S-5001",
    "name": "TechGadgets Inc.",
    "rating": 4.8
  }
}

查找数据

查询包含特定商品的订单

GET /orders/_search   
{
   "query": {
    "nested": {
      "path": "items",
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "items.product_name": "Wireless Headphones"
              }
            },
            {
              "range": {
                "items.price": {
                  "gte": 50
                }
              }
            }
          ]
        }
      }
    }
    }    
}    

关键字:nested

如果要做筛选,nested中的path要写正确

8. Geo_point

特点

  • 用于存储地理位置(经纬度)。

  • 支持地理距离查询。

使用案例

  • 用户位置、商家地址等。

创建 Mapping

一个店铺的位置:

PUT /geo_shops
{
  "mappings": {
    "properties": {
      "shop_id": {
        "type": "keyword"
      },
      "shop_name": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword"
          }
        }
      },
      "location": {
        "type": "geo_point"
      },
      "address": {
        "type": "text"
      },
      "category": {
        "type": "keyword"
      }
    }
  }
}

插入数据

POST /geo_shops/_doc/1   
{
   "shop_id": "S001",
   "shop_name": "Central Coffee",
   "location": {
    "lat": 39.9042,
    "lon": 116.4074
   },
   "address": "1 Wangfujing Street, Beijing",
   "category": "cafe"
}

查找数据

1公里范围查询方法

1.geo_distance 查询(最常用)

GET /geo_shops/_search   
{
   "query": {
    "bool": {
      "must": {
        "match_all": {}
      },
      "filter": {
        "geo_distance": {
          "distance": "1km",
          "location": {
            "lat": 39.9087,
            "lon": 116.3975
            }
            }
            }
            }
            }            
}            

2.带排序的距离查询(按距离由近到远)

GET /geo_shops/_search            
{
  "query": {
    "bool": {
      "filter": {
        "geo_distance": {
          "distance": "1km",
          "location": {
            "lat": 39.9087,
            "lon": 116.3975
          }
        }
      }
    }
  },
  "sort": [
    {
      "_geo_distance": {
        "location": {
          "lat": 39.9087,
          "lon": 116.3975
        },
        "order": "asc",
        "unit": "km",
        "mode": "min",
        "distance_type": "arc"
      }
    }
  ]
}            

3. 返回距离信息的查询

GET /geo_shops/_search
{
  "query": {
    "bool": {
      "filter": {
        "geo_distance": {
          "distance": "1km",
          "location": {
            "lat": 39.9087,
            "lon": 116.3975
          }
        }
      }
    }
  },
  "script_fields": {
    "distance_km": {
      "script": {
        "source": "doc['location'].arcDistance(params.lat, params.lon)",
        "params": {
          "lat": 39.9087,
          "lon": 116.3975
        }
      }
    }
  }
}

4. 组合查询(特定类别+1公里范围)

GET /geo_shops/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "category": "cafe"
          }
        }
      ],
      "filter": {
        "geo_distance": {
          "distance": "1km",
          "location": {
            "lat": 39.9087,
            "lon": 116.3975
          }
        }
      }
    }
  }
}

高级参数说明

  1. distance_type

    • arc(默认):最精确,使用球面计算

    • plane:更快但精度稍低,适用于小范围

  2. mode(多位置文档):

    • min(默认):使用最近的点

    • max:使用最远的点

    • avg:使用平均距离

    • median:使用中位数距离

性能优化建议

  1. 为地理字段使用 doc_values(默认启用)

  2. 对于静态数据,考虑使用 indexed_shape 替代动态计算

  3. 合理设置 precision 和 tree_levels 参数

  4. 使用过滤器(filter)而非查询(query)进行地理过滤,可以利用缓存

创建 Mapping:

插入数据:

查找数据:

字段选型的优化建议

keyword、text 使用建议

场景推荐类型理由示例
精确匹配keyword不分词,完整匹配订单号、ID、标签
全文搜索text + keyword多字段既支持分词搜索又支持精确匹配产品名称、文章标题
多语言内容text + 指定分析器支持语言特性分词中文用ik,英文用standard

Numeric使用合适的类型

减少空间浪费

禁用分词索引

对于不需要分词的字段,禁用索引("index": false)可以显著提升写入性能并减少存储空间,但需注意这些字段将无法被搜索、聚合,只能用于返回原始值(如:产品参数信息)

配置方法

{
   "mappings": {
    "properties": {
      "raw_data": {
        "type": "text",
        "index": false
      }
    }
   }   
}

nested嵌套对象优化

如果nested中只有1个对象(不是数组),可以使用Object类型,甚至可以将子对象属性直接放到父对象中。也可以提取到父对象中,如下

{
  "product_name":"xiaomi",
  "seller_name": "zhangsan",
  "seller_id": 1,
  "buyer_name": "wangwu",
  "buyer_id": 2
}

如果nested中明确数量(学生的成绩分为:语文、数学、英语、政治、历史..),可以将对象设置为如下形式(若是大学的课程,课程种类会变化,则不适合)

-- 原始数据 --
{
  "student_name": "zhangsan",
  "score": [
    {
      "type": "chinese",
      "score": 120
    },
    {
      "type": "english",
      "score": 130
    },
    {
      "type": "math",
      "score": 140
    }
  ]
}

-- 变更后数据 -- 
{
  "student_name":"zhangsan",
  "score_chinese":120,
  "score_english": 130,
  "score_math": 140
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2329625.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

全国产FMC子卡-16bit 8通道2.4G

国产化FMC DA子卡,16bit 8通道2.4GS/s 全国产FMC子卡是一款高分辨率、高采样率的全国产多通道标准双宽DAC FMC子板。其接口电气和结构设计均依据FMC标准(ANSI/VITA 57.1),通过两个高密度FMC连接器(HPC)连接至FPGA载板。它提供8路A…

fpga:分秒计时器

任务目标 分秒计数器核心功能:实现从00:00到59:59的循环计数,通过四个七段数码管显示分钟和秒。 复位功能:支持硬件复位,将计数器归零并显示00:00。 启动/暂停控制:通过按键控制计时的启动和暂停。 消抖处理&#…

小白 thingsboard 拆分前后端分离

1、modules 里注释掉ui_ugx <modules><module>netty-mqtt</module><module>common</module><module>rule-engine</module><module>dao</module><module>edqs</module><module>transport</module&g…

4G专网:企业数字化转型的关键通信基石

4G专网 在数字化转型的浪潮下&#xff0c;企业对高可靠性、低时延、安全可控的通信网络需求日益增长。传统的公用蜂窝网络难以满足企业在工业自动化、能源管理、智慧城市等领域的特殊需求&#xff0c;因此4G专网成为众多行业的优先选择。作为行业领先的移动核心网提供商&#x…

基于FLask的共享单车需求数据可视化分析系统

【FLask】基于FLask的共享单车需求数据可视化分析系统 &#xff08;完整系统源码开发笔记详细部署教程&#xff09;✅ 目录 一、项目简介二、项目界面展示三、项目视频展示 一、项目简介 该系统能够整合并处理大量共享单车使用数据&#xff0c;通过直观的可视化手段&#xff0…

STL 性能优化实战:解决项目中标准模板库的性能瓶颈

&#x1f9d1; 博主简介&#xff1a;CSDN博客专家、全栈领域优质创作者、高级开发工程师、高级信息系统项目管理师、系统架构师&#xff0c;数学与应用数学专业&#xff0c;10年以上多种混合语言开发经验&#xff0c;从事DICOM医学影像开发领域多年&#xff0c;熟悉DICOM协议及…

ES使用聚合aggregations实战(自用:2025.04.03更新)

ES使用聚合aggregations实战 聚合模板桶聚合&#xff1a;Bucket Aggregations指标聚合&#xff1a;Metrics Aggregations管道聚合&#xff1a;Pipeline Aggregations嵌套聚合日期直方图&#xff1a;date-histogram 接口实战接口一&#xff1a;根据stu_id分组统计时间段内的各个…

AI Agent设计模式四:Evaluator

概念 &#xff1a;质量验证与反馈机制 ✅ 优点&#xff1a;自动化质量检查&#xff0c;实现持续优化闭环❌ 缺点&#xff1a;评估准确性依赖模型能力 from typing import TypedDict from langchain_openai import ChatOpenAI from langgraph.graph import StateGraph, START, …

AI绘画中的LoRa是什么?

Lora是一个多义词&#xff0c;根据不同的上下文可以指代多种事物。以下将详细介绍几种主要的含义&#xff1a; LoRa技术 LoRa&#xff08;Long Range Radio&#xff09;是一种低功耗广域网&#xff08;LPWAN&#xff09;无线通信技术&#xff0c;以其远距离、低功耗和低成本的特…

Linux网络:数据链路层以太网

目录 认识数据链路层关于以太网1. 基本概念2. 以太网帧格式3. MAC vs IP 认识数据链路层 数据链路层 位于物理层和网络层之间&#xff0c;其作用是将源自物理层来的数据可靠地传输到相邻节点的目标主机的网络层&#xff0c;主要通过物理介质(如以太网&#xff0c;Wi-Fi等)将数…

MySQL基础 [一] - 数据库基础

目录 什么是数据库 站在服务器角度理解 站在用户角度理解 为什么不直接使用文件存储呢&#xff1f; 主流数据库 MySQL的基本使用 数据库的使用样例 服务器管理 服务器数据库表之间的关系 MySQL的架构 MySQL语句分类 存储引擎 查看存储引擎 存储引擎对比 什么…

【华为OD技术面试真题 - 技术面】- Java面试题(17)

华为OD面试真题精选 专栏:华为OD面试真题精选 目录: 2024华为OD面试手撕代码真题目录以及八股文真题目录 文章目录 华为OD面试真题精选虚拟机分区1. **虚拟磁盘分区**2. **虚拟机的内存分区**3. **CPU分配**4. **虚拟网络分区**5. **存储虚拟化和分区**6. **虚拟机分区管理**…

#Linux内存管理# 在32bit Linux中,内核空间的线性映射的虚拟地址和物理地址是如何换算的?

在32位Linux系统中&#xff0c;内核空间的线性映射&#xff08;也称为直接映射或低端内存映射&#xff09;采用固定的偏移量进行虚拟地址和物理地址的换算。以下是详细的转换规则及背景知识&#xff1a; 1. 32位Linux内存布局 用户空间&#xff1a;虚拟地址 0x00000000 到 0x…

006贪心——算法备赛

跨步问题 跳跃游戏|| 问题描述 给定一个长度为 n 的 0 索引整数数组 nums。初始位置为 nums[0]。 每个元素 nums[i] 表示从索引 i 向后跳转的最大长度。换句话说&#xff0c;如果你在 nums[i] 处&#xff0c;你可以跳转到任意 nums[i j] 处: 0 < j < nums[i]i j &…

pytorch中Dropout

Dropout 是一种常用的正则化技术&#xff0c;用于防止神经网络过拟合。PyTorch 提供了 nn.Dropout 层来实现这一功能。 基本用法 torch.nn.Dropout(p0.5, inplaceFalse) 参数说明&#xff1a; p (float): 每个元素被置为0的概率&#xff08;默认0.5&#xff09; inplace (b…

【玩泰山派】2、制作buildroot镜像,并烧录

文章目录 前言制作buildroot镜像过程搭建环境&#xff08;docker版&#xff09;下载泰山派开发的sdk利用制作的镜像和下载的sdk去启动开发docker容器编译buildroot镜像 参考 前言 泰山派官方提供了不少现成的镜像 但是都买了泰山派了&#xff0c;肯定是想自己编译折腾下&…

初阶数据结构--树

1. 树的概念与结构 树是⼀种⾮线性的数据结构&#xff0c;它是由 n&#xff08;n>0&#xff09; 个有限结点组成⼀个具有层次关系的集合。把它叫做 树是因为它看起来像⼀棵倒挂的树&#xff0c;也就是说它是根朝上&#xff0c;⽽叶朝下的。 有⼀个特殊的结点&#xff0c;称…

安装gpu版本的dgl

1.先去网址&#xff0c;找到对应版本的dgl,然后下载到本地。 dgl-whl下载地址 我的是python 3.8 &#xff0c;cuda 11.6. windows 2.在虚拟环境里 输入 pip install E:\dgl-1.0.2cu116-cp38-cp38-win_amd64.whl &#xff08;因为我下载到E盘里了&#xff09; 这样GPU版本的d…

5天速成ai agent智能体camel-ai之第1天:camel-ai安装和智能体交流消息讲解(附源码,零基础可学习运行)

嗨&#xff0c;朋友们&#xff01;&#x1f44b; 是不是感觉AI浪潮铺天盖地&#xff0c;身边的人都在谈论AI Agent、大模型&#xff0c;而你看着那些密密麻麻的代码&#xff0c;感觉像在读天书&#xff1f;&#x1f92f; 别焦虑&#xff01;你不是一个人。很多人都想抓住AI的风…

FPGA——FPGA状态机实现流水灯

一、引言 在FPGA开发中&#xff0c;状态机是一种重要的设计工具&#xff0c;用于处理具有时间顺序的事件。本文将详细介绍如何使用状态机实现一个LED流水灯的效果。 二、状态机概述 状态机&#xff08;FSM&#xff09;是一种行为模型&#xff0c;用于表示系统在不同状态下的…