文章目录
ElasticSearch 简介
ElasticSearch是一个高度可扩展的开源搜索引擎并使用REST API,所以您值得拥有。 在本教程中,将介绍开始使用ElasticSearch的一些主要概念。
下载并运行ElasticSearch
ElasticSearch可以从elasticsearch.org下载对应的文件格式,如ZIP和TAR.GZ。下载并提取一个运行它的软件包之后不会容易得多,需要提前安装Java运行时环境。
下载链接 https://www.elastic.co/products/elasticsearch
在Windows上运行ElasticSearch
- 从命令窗口运行位于bin文件夹中的elasticsearch.bat。这将会启动ElasticSearch在控制台的前台运行,这意味着我们可在控制台中看到运行信息或一些错误信息,并可以使用CTRL + C停止或关闭它。
- 在启动过程中,ElasticSearch的实例运行会占用大量的内存,所以在这一过程中,电脑会变得比较慢,需要耐心等待,启动加载完成后电脑就可以正常使用了
- 当ElasticSearch的实例并运行,您可以使用http://localhost:9200检查是否运行成功
安装ik中文分词器
下载地址:https://github.com/medcl/elasticsearch-analysis-ik/releases
- 选择和已经下载的elasticsearch版本兼容的ik。
- 解压后复制
elasticsearch/plugins
目录下 - 重新运行
elasticsearch.bat
ik测试使用
可以使用谷歌的
Postman
工具测试
创建一个索引:
curl -XPUT http://localhost:9200/index
创建一个映射
curl -XPOST http://localhost:9200/index/fulltext/_mapping -H 'Content-Type:application/json' -d'
{
"properties": {
"content": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
}
}
}'
添加索引文档测试数据
curl -XPOST http://localhost:9200/index/fulltext/1 -H 'Content-Type:application/json' -d'
{"content":"美国留给伊拉克的是个烂摊子吗"}
curl -XPOST http://localhost:9200/index/fulltext/2 -H 'Content-Type:application/json' -d'
{
"content":"公安部:各地校车将享最高路权"}
curl -XPOST http://localhost:9200/index/fulltext/3 -H 'Content-Type:application/json' -d'
{"content":"中韩渔警冲突调查:韩警平均每天扣1艘中国渔船"}
curl -XPOST http://localhost:9200/index/fulltext/4 -H 'Content-Type:application/json' -d'
{
"content":"中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首"}
查询突出显示
curl -XPOST http://localhost:9200/index/fulltext/_search -H 'Content-Type:application/json' -d'
{
"query" : {
"match" : {
"content" : "中国" }},
"highlight" : {
"pre_tags" : ["<tag1>", "<tag2>"],
"post_tags" : ["</tag1>", "</tag2>"],
"fields" : {
"content" : {
}
}
}
}
返回结果
{
"took": 14,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 2,
"max_score": 2,
"hits": [
{
"_index": "index",
"_type": "fulltext",
"_id": "4",
"_score": 2,
"_source": {
"content": "中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首"
},
"highlight": {
"content"