ElasticSearch的使用

本文详细介绍了如何使用Elasticsearch进行索引的创建、删除及映射表的管理,包括通过DevTools和curl命令操作,以及如何进行type和mapping的新增与修改。并强调了高版本ES对String类型的弃用。

创建和删除索引

使用DevTools

 PUT test001
 DELETE test001

使用curl

curl -X PUT "http://10.5.145.101:9200/productindex"
curl -X DELETE "http://10.5.145.101:9200/productindex"

注意索引名称都是小写字母才行。

  • 创建type和对应的映射表
    查看
curl -XGET "http://10.5.145.101:9200/trolley/_mapping?pretty"
GET trolley/_mapping?pretty

新建type和对应的mapping
DEVTools

POST trolley/product/_mapping?pretty 
{
    "product": {
            "properties": {
                "price": {
                    "type": "double"
                },
                "onSale": {
                    "type": "boolean"
                },
                "type": {
                    "type": "integer"
                },
                "createDate": {
                    "type": "date"
                }
            }
        }
  }

注意,ES高版本中不再支持String,请不要在写Spring了。
增量修改mapping

POST trolley/product/_mapping?pretty 
{
     "product": {
                "properties": {
                     "amount":{
                        "type":"text"
                   }
                }
            }
    }

ES不支持非增量修改index,如果要修改,只能删除然后重建。

简单查询

POST /trolley/_search
{
  "query": { "match": { "eventType": "ISSUE" } }
}
### 使用Elasticsearch进行搜索和数据分析 #### 安装与初始化 要使用 Elasticsearch 进行操作,首先需要创建一个 Elasticsearch 客户端实例。这可以通过 Python 的 `elasticsearch` 库实现[^2]。 ```python from elasticsearch import Elasticsearch es_client = Elasticsearch(hosts=["http://localhost:9200"]) if es_client.ping(): print("成功连接到Elasticsearch!") else: print("无法连接到Elasticsearch.") ``` #### 数据索引 为了使数据可被搜索和分析,需先将其存入 Elasticsearch 中的一个索引里。以下展示了如何向名为 `myindex` 的索引中添加文档[^1]: ```json POST /myindex/_doc/ { "title": "Elasticsearch基础", "content": "Elasticsearch是一个强大的搜索和分析引擎,它可以帮助我们高效地处理和分析大量数据。" } ``` 上述 JSON 请求会将一条记录写入指定的索引中。每条记录都有字段(如 title 和 content),这些字段可以用于后续查询和聚合操作。 #### 基本搜索 执行基本搜索可通过发送 GET 请求完成。例如,查找所有包含特定关键词的内容[^4]: ```json GET /myindex/_search { "query": { "match": { "content": "强大" } } } ``` 此请求会在 `content` 字段中寻找含有 “强大” 关键词的所有文档。 #### 高级数据分析——聚合功能 除了简单的搜索外,Elasticsearch 提供了丰富的聚合功能来支持复杂的数据分析需求[^3]。比如统计某个字段的不同取值及其频率: ```json GET /myindex/_search { "size": 0, "aggs": { "unique_titles": { "terms": { "field": "title.keyword", "size": 10 } } } } ``` 这段代码实现了基于 `title` 字段的分组计数,并返回前十个最常见的标题。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值