本文内容部分使用AI生成技术

目的

本文总结了关于ES从安装到一些常见的关于ES的API使用示例,方便可以后面快速查询使用。

一、下载安装ES

1.下载:
下载地址 7.10.2
2.安装
下载完成后解压,并执行以下命令启动:

# 执行解压后目录下的 /bin/elasticsearch 命令启动
> cd /Users/mac/dev/elasticsearch/elasticsearch-7.10.2
> ./bin/elasticsearch 

3.登录
浏览器输入:https://localhost:9200/
账号:elastic
密码:复制日志中打印的密码:

Password for the elastic user (reset with `bin/elasticsearch-reset-password -u elastic`):
  lvxxxxxxxxxx

4.安装 Chrome ElasticVue 扩展程序(可选)
5.解决SSL报错(可选)
关闭后不用使用https访问

vim config/elasticsearch.yml
修改:
# 关闭安全功能
xpack.security.enabled: false
# 关闭 HTTP 层的 SSL
xpack.security.http.ssl.enabled: false

6.安装ik分词器插件

bin/elasticsearch-plugin install https://get.infini.cloud/elasticsearch/analysis-ik/7.10.2

二、ES使用

主要分为两大类别:
1.对索引(相当于数据库的DDL)的操作
2.对文档(相当于数据库的DML)的操作

1、ES索引

创建索引

PUT /product/_mapping
{
  "mappings": {
    "properties": {
      "product_name": { 
        "type": "text",  // 【规则】Text类型:用于全文搜索。存入“华为Mate60 Pro”会被分词为【华为、Mate60、Pro】。
        "analyzer": "ik_max_word",  // 使用IK中文分词
        "fields": {     // 多字段特性:一个字段以两种方式索引。
          "keyword": { 
            "type": "keyword"  // 【规则】Keyword类型:用于精确匹配、聚合、排序。存入的是完整的“华为Mate60 Pro”字符串。
          }
        }
      },
      "brand": { 
        "type": "keyword" // 品牌名通常用于精确过滤(如`品牌=小米`)或聚合统计,故用keyword。
      },
      "price": { "type": "float" },
      "title": {
          "type": "text",
          "analyzer": "ik_max_word",  // 使用IK中文分词
          "search_analyzer": "ik_smart"
      },
      "create_time": {
          "type": "date",
          "format": "yyyy-MM-dd HH:mm:ss"
      },
      "tags": { "type": "keyword" }  // 标签也适合精确匹配和聚合。精确值,用于过滤、聚合
    }
  },
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 2
  }
}

2、ES文档

添加文档

// 1. 创建单个文档 (指定ID)
PUT /product/_doc/1
{ "product_name": "华为Mate60 Pro", "brand": "华为", "price": 6999, "tags": ["手机", "旗舰", "新品"] ,
"title": "小米手机", "create_time": "2023-10-01 12:00:00"}

// 2. 批量操作(高效增删改)
POST /_bulk
{"index":{"_index":"product","_id":"2"}}
{"product_name":"iPhone 15","brand":"苹果","price":5999,"tags":["手机","iOS"],"title":"苹果手机","create_time":"2024-10-01 12:00:00"}
{"index":{"_index":"product","_id":"3"}}
{"product_name":"小米13 Ultra","brand":"小米","price":6499,"tags":["手机","相机","旗舰"],"title":"小米13 Ultra 徕卡影像旗舰","create_time":"2025-10-01 12:00:00"}

查询文档(重点)

规则 对应查询类型 应用场景与示例
bool: 组合多个查询条件 bool 组合 必须满足(must)、应该满足(should)、必须不满足(must_not)和过滤(filter) 条件。
must: 必须满足,参与算分 嵌套在 bool 内 影响结果相关度排序的核心条件。
filter: 必须满足,不参与算分 嵌套在 bool 内 用于结构化数据过滤(范围、状态),不关心相关性,性能更优。
should: 应该满足(或逻辑) 嵌套在 bool 内 实现“或”逻辑,常与 minimum_should_match 配合。
must_not: 必须不满足 嵌套在 bool 内 排除不需要的数据。
match: 对查询词分词,模糊匹配 match, multi_match 在商品名称、描述中进行关键词搜索。
term: 不对查询词分词,精确匹配 term, terms 对keyword字段进行精确筛选,如品牌、状态码、标签。

!!! 查询嵌套优先级:
query → [ bool → must/must not/filter/should → ] term/terms/match
“[ ]”中的关键词为可选
其中:
must/must not/filter/should: 决定了是否对【文档】进行分词以及是否计算得分
term/terms/match: 控制查询【关键词】是否进行分词处理

简单查询
# 基础匹配查询
POST /product/_search
{
  "query": {
    "match": {
      "title": "小米手机"
    }
  },
  "from": 0,
  "size": 10
}

# 多字段搜索
POST /product/_search
{
  "query": {
    "multi_match": {
      "query": "小米",
      "fields": ["title", "brand^2"]  // brand字段权重加倍
    }
  }
}

复杂查询

# 精确过滤与范围查询
POST /product/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "title": "手机" } }
      ],
      "filter": [
        { "term": { "brand": "小米" } },
        { "range": { "price": { "gte": 3000, "lte": 5000 } } },
        { "exists": { "field": "tags" } }
      ]
    }
  }
}

# 复杂布尔组合
POST /product/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "title": "手机" } }
      ],
      "should": [
        { "term": { "tags": "新品" } },
        { "range": { "price": { "lte": 4000 } } }
      ],
      "minimum_should_match": 1,
      "must_not": [
        { "term": { "brand": "苹果" } }
      ]
    }
  }
}

# 指标与分组聚合
POST /product/_search
{
  "size": 10,
  "aggs": {
    "price_stats": {
      "stats": { "field": "price" }  // 统计: 计数、总和、平均、最小、最大
    },
    "group_by_brand": {
      "terms": { "field": "brand" },  // 按品牌分组
      "aggs": {
        "avg_price": { "avg": { "field": "price" } }  // 每个品牌的平均价格
      }
    },
    "price_histogram": {
      "histogram": {
        "field": "price",
        "interval": 1000,
        "extended_bounds": { "min": 0, "max": 10000 }
      }
    }
  }
}

# 时间范围统计
POST /product/_search
{
  "size": 10,
  "aggs": {
    "sales_over_time": {
      "date_histogram": {
        "field": "create_time",
        "calendar_interval": "month",
        "format": "yyyy-MM"
      },
      "aggs": {
        "total_sales": { "sum": { "field": "price" } }
      }
    }
  }
}

# 全文检索(高亮显示)
POST /product/_search
{
  "query": {
    "match": { "title": "智能手机" }
  },
  "highlight": {
    "fields": {
      "title": {
        "pre_tags": ["<em>"],
        "post_tags": ["</em>"]
      }
    }
  }
}
整体示例
POST /product/_search
{
  "from": 0,
  "size": 10,
  "query": {
    "bool": {
      "must": [
        {
          "multi_match": {
            "query": "小米手机",
            "fields": [
              "title^2",
              "brand^1.5"
            ],
            "type": "best_fields"
          }
        }
      ],
      "should": [
        {
          "term": {
            "tags": "旗舰"
          }
        },
        {
          "range": {
            "price": {
              "lte": 4000
            }
          }
        }
      ],
      "minimum_should_match": 1,
      "filter": [
        {
          "term": {
            "brand": "小米"
          }
        },
        {
          "range": {
            "price": {
              "gte": 2000,
              "lte": 8000
            }
          }
        },
        {
          "exists": {
            "field": "tags"
          }
        }
      ],
      "must_not": [
        {
          "term": {
            "brand": "苹果"
          }
        }
      ]
    }
  },
  "highlight": {
    "fields": {
      "title": {
        "pre_tags": [
          "<em>"
        ],
        "post_tags": [
          "</em>"
        ]
      },
      "brand": {}
    }
  },
  "aggs": {
    "price_stats": {
      "stats": {
        "field": "price"
      }
    },
    "group_by_brand": {
      "terms": {
        "field": "brand",
        "size": 10
      },
      "aggs": {
        "avg_price": {
          "avg": {
            "field": "price"
          }
        },
        "brand_price_stats": {
          "stats": {
            "field": "price"
          }
        }
      }
    },
    "price_histogram": {
      "histogram": {
        "field": "price",
        "interval": 1000,
        "extended_bounds": {
          "min": 0,
          "max": 10000
        }
      }
    },
    "sales_over_time": {
      "date_histogram": {
        "field": "create_time",
        "calendar_interval": "month",
        "format": "yyyy-MM-dd",
        "min_doc_count": 0,
        "extended_bounds": {
          "min": "2024-01-01",
          "max": "2025-12-31"
        }
      },
      "aggs": {
        "monthly_revenue": {
          "sum": {
            "field": "price"
          }
        }
      }
    }
  }
}

参考文档:
https://www.elastic.co/docs/reference/elasticsearch/rest-apis#documenthttpswww.elastic.codocsapidocelasticsearchv9groupendpoint-document

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐