#打卡不停更# 如何搭建与使用ElasticSearch 原创

zhushangyuan_
发布于 2022-10-20 09:52
浏览
0收藏

如何搭建与使用ElasticSearch

1、Ubuntu安装

访问 https://www.elastic.co/cn/downloads/past-releases/elasticsearch-7-10-1 下载安装包。

  • 对于Ubuntu平台
    可以下载DEB X86_64,然后执行命令安装:
sudo dpkg -i elasticsearch-7.10.1-amd64.deb

2、启动停止

  • 启动停止命令
sudo service elasticsearch start
sudo service elasticsearch status
sudo service elasticsearch stop
  • 后台启动:
nohup ./bin/elasticsearch&
  • 执行下述命令验证:
curl -X GET "localhost:9200"
  • 返回结果如下:
{
  "name" : "DESKTOP-RPE9R4O",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "4sOiKfDYR0ydlwxXYT1j4g",
  "version" : {
    "number" : "7.10.1",
    "build_flavor" : "default",
    "build_type" : "deb",
    "build_hash" : "1c34507e66d7db1211f66f3513706fdf548736aa",
    "build_date" : "2020-12-05T01:00:33.671820Z",
    "build_snapshot" : false,
    "lucene_version" : "8.7.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

3、ElasticSearch配置

sudo vi /etc/elasticsearch/elasticsearch.yml

配置项network.host可以指定可以访问ES服务的主机,注释掉,或者指定为localhost,则只允许本地访问。

. . .
# ---------------------------------- Network -----------------------------------
#
# Set the bind address to a specific IP (IPv4 or IPv6):
#
network.host: localhost
. . .

配置外网访问9200端口 需要开放服务器的端口:

# 修改配置文件 config/elasticsearch.yml
network.host: 0.0.0.0

4、 使用ElasticSearch

4.1 索引一个文档

索引可以理解为保存到数据库,可以使用cURL来演示如何索引一个文档Indexing a simple document using cURL。
执行如下命令来演示,其中id是数据编号,请求的URI为/tutorial/helloworld/1:

  • tutorial 为数据索引index.
  • helloworld 类型type.
  • 1 指定索引和类型下的数据条目编号.
curl -XPOST -H "Content-Type: application/json" 'http://localhost:9200/tutorial/helloworld/1?pretty' -d '{"message": "Hello World!"}'

通过下面的地址在浏览器访问,可以查询数据:

http://localhost:9200/tutorial/helloworld/1?pretty
http://localhost:9200/tutorial/helloworld/_search?pretty

再看一个例子:

curl -XPOST -H "Content-Type: application/json" "HTTP://localhost:9200/my_first_index/message?pretty" -d'{"text": "Hello world!"}'

4.2 查询搜索

搜索 find it by searching for “hello”:

  curl -XPOST -H "Content-Type: application/json" "http://localhost:9200/_search?pretty" -d'
  {
     "query": {
        "query_string": {
            "query": "hello"
          }
       }
  }'

搜索出来两个:

{
	"took": 3,
	"timed_out": false,
	"_shards": {
		"total": 2,
		"successful": 2,
		"skipped": 0,
		"failed": 0
	},
	"hits": {
		"total": {
			"value": 2,
			"relation": "eq"
		},
		"max_score": 0.2876821,
		"hits": [{
			"_index": "my_first_index",
			"_type": "message",
			"_id": "lvtwioEBVhuqQbcbG2dr",
			"_score": 0.2876821,
			"_source": {
				"text": "Hello world!"
			}
		}, {
			"_index": "tutorial",
			"_type": "helloworld",
			"_id": "1",
			"_score": 0.2876821,
			"_source": {
				"message": "Hello World!"
			}
		}]
	}
}

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
收藏
回复
举报
回复
    相关推荐