ElasticSearch基本操作

发布时间 2023-06-21 16:07:12作者: iyandongsheng

索引

  • 创建索引
查看代码
 PUT / HTTP/1.1
Host: http://127.0.0.1:9200/shopping
//shopping 为索引名
  • 查看单个索引信息
查看代码
 GET / HTTP/1.1
Host: http://127.0.0.1:9200/shopping
  • 查看所有索引信息
查看代码
 GET /indices?v HTTP/1.1
Host: http://127.0.0.1:9200/_cat
  • 删除索引
查看代码
 DELETE / HTTP/1.1
Host: http://127.0.0.1:9200/shopping

 

文档

  •  创建(不指定主键)
查看代码
 POST /_doc HTTP/1.1
Host: http://127.0.0.1:9200/shopping
Content-Type: application/json
Content-Length: 33

{
    "name":"张三",
    "age":20
}
  •  创建(指定主键)
查看代码
 POST /_doc/1001 HTTP/1.1
Host: http://127.0.0.1:9200/shopping
Content-Type: application/json
Content-Length: 33

{
    "name":"李四",
    "age":20
}
  •  创建(指定主键、幂等操作可以设置PUT)
查看代码
 PUT /_doc/1001 HTTP/1.1
Host: http://127.0.0.1:9200/shopping
Content-Type: application/json
Content-Length: 33

{
    "name":"李四",
    "age":20
}
  •  主键查询
查看代码
 GET /_doc/1001 HTTP/1.1
Host: http://127.0.0.1:9200/shopping
  •  查询所有数据
GET /_search HTTP/1.1
Host: http://127.0.0.1:9200/shopping

查询结果为:

查看代码
 {
    "took": 11,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 2,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "zYTd3IgBSg2Z_d79qWOf",
                "_score": 1.0,
                "_source": {
                    "name": "张三",
                    "age": 20
                }
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "1001",
                "_score": 1.0,
                "_source": {
                    "name": "李四",
                    "age": 20
                }
            }
        ]
    }
}
  •  更新数据

修改数据分为全部更新(幂等性可用PUT)和部分更新(非幂等)。

    • 全部修改(幂等)
查看代码
PUT /_doc/1001 HTTP/1.1
Host: http://127.0.0.1:9200/shopping
Content-Type: application/json
Content-Length: 36

{
    "name": "张三",
    "age": 30
 }

操作结果:

查看代码
{
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1001",
    "_version": 3,
    "result": "updated",
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 3,
    "_primary_term": 1
}
    •  局部更新(非幂等)
查看代码
 POST /_update/1001 HTTP/1.1
Host: http://127.0.0.1:9200/shopping
Content-Type: application/json
Content-Length: 40

{
    "doc":{
        "age": 35
    }
 }

 操作结果

查看代码
 {
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1001",
    "_version": 4,
    "result": "updated",
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 4,
    "_primary_term": 1
}
  •  删除数据
查看代码
 DELETE /_doc/1001 HTTP/1.1
Host: http://127.0.0.1:9200/shopping