运行 elasticsearch-5.6.1\bin\elasticsearch.bat 启动ElasticSearch。
浏览器访问 http://127.0.0.1:9200/, 查看ElasticSearch是否运行正常。
{
"name" : "-nHCtwI",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "3efB1ZQnQmmlGnDOldGRdQ",
"version" : {
"number" : "5.6.1",
"build_hash" : "667b497",
"build_date" : "2017-09-14T19:22:05.189Z",
"build_snapshot" : false,
"lucene_version" : "6.6.1"
},
"tagline" : "You Know, for Search"
}
通过REST接口添加数据, Index 相当于数据库,type相当于数据库中的表。本例子中
Index是product,type是book,主键是1:
curl http://127.0.0.1:9200/product/book/1?pretty -XPOST -H 'application/json' -d '{"name":"My Book", "type":"Java", "price": 100}'
添加成功后返回:
{
"_index" : "product",
"_type" : "book",
"_id" : "1",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"created" : true
}
查询刚才添加的数据
curl http://127.0.0.1:9200/product/book/1?pretty -XGET
返回:
{
"_index" : "product",
"_type" : "book",
"_id" : "1",
"_version" : 1,
"found" : true,
"_source" : {
"name" : "My Book",
"type" : "Java",
"price" : 100
}
}
全文搜索:curl "http://127.0.0.1:9200/product/book/_search?pretty&q=type:java"
返回:
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : 0.2876821,
"hits" : [
{
"_index" : "product",
"_type" : "book",
"_id" : "1",
"_score" : 0.2876821,
"_source" : {
"name" : "My Book",
"type" : "Java",
"price" : 100
}
}
]
}
}
_score是分值,越大表示匹配度越高。上面的例子也可以这样查询,结果是一样的。
curl "http://127.0.0.1:9200/product/book/_search?pretty" -d '{"query":{"match": {"type": "java"}}}'
也可以精确查询:
curl "http://127.0.0.1:9200/product/book/_search?pretty" -d '{"query":{"term": {"type": "java"}}}'
可以只查询数量:
curl "http://127.0.0.1:9200/product/book/_count?pretty" -d '{"query":{"match": {"type": "java"}}}'返回结果:
{
"count" : 1,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
}
}
可以限制查询结果数量:
curl "http://127.0.0.1:9200/product/book/_search?pretty" -d '{"size":1, "query":{"term": {"type": "java"}}}'
联合查询:
curl "http://127.0.0.1:9200/product/book/_search?pretty" -d
'{
"size":1,
"query":{
"bool": {
"must": {"match": {"type": "java"}},
"must":{"match": {"name": "book"}}
}
}
}'
另外也可以查询所有Index下 type为book的数据:
curl "http://127.0.0.1:9200/*/book/_search?pretty" -d '{"size":1, "query":{"term": {"type": "java"}}}'
或者:
curl "http://127.0.0.1:9200/_all/book/_search?pretty" -d '{"size":1, "query":{"term": {"type": "java"}}}'
查询价格范围:
curl "http://127.0.0.1:9200/product/book/_search?pretty" -d '{"size":1, "query":{"bool": { "must": {"range": {"price":{"from":50, "to": 100 }}}}}}'
对查询结果排序:
curl "http://127.0.0.1:9200/product/book/_search?pretty" -d '{"sort":[{"price":{"order": "desc"}}], "query":{"match": {"type": "java"}}}'