Elasticsearch是一个基于Lucene的搜索服务,它通过倒排索引的方法提供了全文搜索的能力。
1、插入数据
Elasticsearch中存放数据的为文档,有索引及类型名,如下插入两文档:
curl -X PUT "elasticsearch.in.netwa.cn:9200/my_index/my_type/1" -H 'Content-Type: application/json' -d'
{
"first_name" : "小明",
"last_name" : "Smith",
"age" : 25,
"about" : "I love to go rock climbing",
"interests": [ "sports", "music" ]
}
'
curl -X PUT "elasticsearch.in.netwa.cn:9200/my_index/my_type/2" -H 'Content-Type: application/json' -d'
{
"first_name" : "小红",
"last_name" : "Smith",
"age" : 28,
"about" : "I like to collect rock albums",
"interests": [ "music" ]
}
'
2、检索文档
1)检索id为1的文档
curl -X GET "elasticsearch.in.netwa.cn:9200/my_index/my_type/1"
2)搜索1000个文档(此处没有1000个那就搜索所有)
curl -i -XGET 'http://elasticsearch.in.netwa.cn:9200/my_index/my_type/_search?size=1000'
3)搜索指定字段值的文档(采用模糊匹配的方法)
curl -X POST "elasticsearch.in.netwa.cn:9200/my_index/my_type/_search" -H 'Content-Type: application/json' -d'
{
"query": {
"match" : { "first_name" : "小红" }
}
}
'
4)检索所有文档的数量
curl -i -XGET 'http://elasticsearch.in.netwa.cn:9200/_count?pretty' -H 'content-type: application/json' -d '
{"query":{"match_all":{}}}'
3、删除索引
1)删除所有索引
curl -i -XDELETE 'elasticsearch.in.netwa.cn:9200/_all'
2)删除指定索引
curl -i -XDELETE 'elasticsearch.in.netwa.cn:9200/my_index'
4、精确查询
term查询代表完全匹配,不进行分词器分析,文档中必须包含整个搜索的词汇。
进行精确确查询时必须首先创建映射索引,此时需要注意Elasticsearch版本
1)创建映射索引(版本6.3)
curl -X PUT "elasticsearch.in.netwa.cn:9200/my_index" -H 'Content-Type: application/json' -d'
{
"mappings": {
"my_type": {
"properties": {
"first_name": {"type": "keyword"},
}
}
}
}
'
2)通过映射精确查询(term)
curl -X POST "elasticsearch.in.netwa.cn:9200/question_v1_index/question_v1_type/_search?size=6" -H 'Content-Type: application/json' -d'
{
"query": {
"term" : { "first_name" : "小红" }
}
}
'
5、多个条件同时查询
bool字段下一个数组同时查询多个条件
curl -X POST "elasticsearch.in.netwa.cn:9200/question_v1_index/question_v1_type/_search?size=6" -H 'Content-Type: application/json' -d'
{
"query": {
"bool": {
"must": [
{"term": {"first_name": "小红"}},
{"match": {"last_name": "Smith"}}
]
}
}
}
}
'
https://www.elastic.co/guide/en/elasticsearch/reference/6.3/query-dsl-term-query.html