ElasticSearch 初识

elasticsearch官网:https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html


基本操作

# 创建一个索引,名称为 customer
curl -XPUT 'localhost:9200/customer?pretty'

# 给索引 customer 添加id为1的 document,
curl -XPUT 'localhost:9200/customer/_doc/1?pretty' -H 'Content-Type: application/json' -d'
{
  "name": "John Doe"
}
'

# 给索引添加document时也可以不指定id,这样,es就会生成一个随机id.如:
curl -XPOST 'localhost:9200/customer/_doc?pretty&pretty' -H 'Content-Type: application/json' -d'
{
  "name": "Jane Doe"
}
'


# 查看 索引 customer 的id为1的 docment
curl -XGET 'localhost:9200/customer/_doc/1?pretty'

# 删除索引 customer
curl -XDELETE 'localhost:9200/customer?pretty'

# 查看所有索引状态
curl -XGET 'localhost:9200/_cat/indices?v&pretty'

update document

1.更新索引为customerid为1的document


curl -XPOST 'localhost:9200/customer/_doc/1/_update?pretty&pretty' -H 'Content-Type: application/json' -d'
{
  "doc": { "name": "Jane Doe" }
}
'

2.更新document并且添加一个字段(filed) 为age


curl -XPOST 'localhost:9200/customer/_doc/1/_update?pretty&pretty' -H 'Content-Type: application/json' -d'
{
  "doc": { "name": "Jane Doe", "age": 20 }
}
'

3.使用脚本更新document

curl -XPOST 'localhost:9200/customer/_doc/1/_update?pretty&pretty' -H 'Content-Type: application/json' -d'
{
  "script" : "ctx._source.age += 5"
}
'

其中,ctx._source 代表当前被更新的document对象.

Batch Processing(批处理操作)

elactissearch提供了一个 _bulk API,来进行批处理操作.

1. 批量添加id为1和2的document.

curl -XPOST 'localhost:9200/customer/_doc/_bulk?pretty&pretty' -H 'Content-Type: application/json' -d'
{"index":{"_id":"1"}}
{"name": "John Doe" }
{"index":{"_id":"2"}}
{"name": "Jane Doe" }
'

更新id为1删除id为2的批处理操作.

curl -XPOST 'localhost:9200/customer/_doc/_bulk?pretty&pretty' -H 'Content-Type: application/json' -d'
{"update":{"_id":"1"}}
{"doc": { "name": "John Doe becomes Jane Doe" } }
{"delete":{"_id":"2"}}
'

The Search API(搜索API)

我们有两种方法在es中进行搜索:

  1. REST request URI
  2. REST request body

REST request body允许我们用表达形式更加丰富的 JSON 格式的数据搜索.所以通常来说,我们都是采用第二种方法.

举例:

为了方便,我们使用了官网上的bank数据进行搜索.首先我们要导入我们搜索的数据.
参考:
https://www.elastic.co/guide/en/elasticsearch/reference/current/_the_search_api.html

接下来我们就可以对我们刚导入的 bank 数据进行搜索了.

1.REST request URI

curl -XGET 'localhost:9200/bank/_search?q=*&sort=account_number:asc&pretty&pretty'

2.REST request body

curl -XPOST 'localhost:9200/bank/_search?pretty' -H 'Content-Type: application/json' -d'
{
  "query": { "match_all": {} },
  "sort": [
    { "account_number": "asc" }
  ]
}
'

上面两种方式效果等同.

springboot使用jest连接操作elasticsearch

参考jest官网介绍: https://github.com/searchbox-io/Jest/tree/master/jest

猜你喜欢

转载自blog.csdn.net/itguangit/article/details/79632201