学习

入门指南

Prasan Kumar
作者
Prasan Kumar, Redis 的技术解决方案开发者
Will Johnston
作者
Will Johnston, Redis 的开发者增长经理

欢迎来到官方 Redis 开发者中心的入门指南!

如果你是 Redis 新手,我们建议从 Redis 大学 (RU101) 开始。RU101 是一门入门课程,非常适合 Redis 新手开发者。在这门课程中,你将学习 Redis 的数据结构,并了解如何在实际世界中应用它们。

如果你有 Redis 相关的问题,请加入 Redis Discord 服务器。我们的 Discord 服务器是一个学习、分享和协作关于 Redis 一切事物的地方。与社区用户和 Redis 大学的学员联系。解答你的问题,学习新的实用技巧!关注来自 Redis 和社区的最新内容通知。并与社区分享你自己的内容。

设置 Redis#

使用 Redis 主要有两种方式

  • Cloud Redis:一种托管的无服务器 Redis 数据库即服务 (DBaaS)。这是通过 Amazon AWS、Google Cloud Platform 或 Microsoft Azure 部署 Redis Cloud 的最快方式。
  • 本地部署/本地 Redis:使用你自己的服务器和任何操作系统(Mac OS、Windows 或 Linux)进行自托管 Redis。

如果你选择使用本地 Redis,我们强烈建议使用 Docker。如果你选择不使用 Docker,请根据你的操作系统使用以下说明:

下面的 docker run 命令将 redis-server 暴露在 6379 端口,RedisInsight 暴露在 8001 端口。你可以通过浏览器访问 http://localhost:8001 使用 RedisInsight。

# install
$ docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:latest

你可以使用 redis-cli 连接到 localhost:6379 的服务器。如果你本地没有安装 redis-cli,可以像下面这样从 Docker 容器中运行它:

# connect
$ docker exec -it redis-stack redis-cli

使用 Redis 进行基本查询#

  • 使用 CLI 或 RedisInsight (一个可视化数据和运行命令的 GUI 工具)连接到 Redis

RedisInsight

# syntax 1 : connect using host & port, followed by password
$ redis-cli -h host -p port
> AUTH password
OK

# example 1
$ redis-cli -h redis15.localnet.org -p 6390
> AUTH myUnguessablePassword
OK

# syntax 2 : connect using uri
$ redis-cli -u redis://user:password@host:port/dbnum

# example 2
$ redis-cli -u redis://LJenkins:p%[email protected]:16379/0
  • 基本的 CLI / RedisInsight 工作台命令
# syntax : Check specific keys
> KEYS pattern

# example
> KEYS *

#------------
# syntax : Check number of keys in database
> DBSIZE

#------------
# syntax : set a key value
> SET key value EX expirySeconds

# example
> SET company redis EX 60

#------------
# syntax : get value by key
> GET key

# example
> GET company

#------------
# syntax : delete keys
> DEL key1 key2 key3 ... keyN

# example
> DEL company

#------------
# syntax : Check if key exists
> EXISTS key1

# example
> EXISTS company

#------------
# syntax : set expiry to key
> EXPIRE key seconds

# example
> EXPIRE lastname 60

#------------
# syntax : remove expiry from key
> PERSIST key

# example
> PERSIST lastname

#------------
# syntax : find (remaining) time to live of a key
> TTL key

# example
> TTL lastname

#------------
# syntax : increment a number
> INCR key

# example
> INCR counter

#------------
# syntax : decrement a number
> DECR key

# example
> DECR counter

详细的 CLI 说明可以在 这里查看,命令可以在 这里查看

使用 Redis 进行二级索引和搜索#

Redis Stack 在 Redis 中启用了 JSON 数据类型。

# syntax : set an object value to a key
> JSON.SET objKey $ value

# example
> JSON.SET person $ '{"name":"Leonard Cohen","dob":1478476800,"isActive": true, "hobbies":["music", "cricket"]}'

#------------
# syntax : get object value of a key
> JSON.GET objKey $

# example
> JSON.GET person $

#------------
# syntax : find object key length
> JSON.OBJLEN objKey $

# example
> JSON.OBJLEN person $

#------------
# syntax : find object keys
> JSON.OBJKEYS objKey $

# example
> JSON.OBJKEYS person $

#------------
# syntax : update nested property
> JSON.SET objKey $.prop value

# example
> JSON.SET person $.name '"Alex"'

#------------
# syntax : update nested array
> JSON.SET objKey $.arrayProp fullValue
> JSON.SET objKey $.arrayProp[index] value

# example
> JSON.SET person $.hobbies '["music", "cricket"]'
> JSON.SET person $.hobbies[1] '"dance"'

#------------
# syntax : remove nested array item by index
> JSON.ARRPOP objKey $.arrayProp index

# example
> JSON.ARRPOP person $.hobbies 1

更多详细信息请参阅 Redis Stack 文档

Redis Stack 为 Redis 提供了一个查询和索引引擎,支持二级索引、全文搜索和聚合功能。

  • 我们必须在 schema 上创建索引才能搜索其数据
# syntax
> FT.CREATE {index_name} ON JSON PREFIX {count} {prefix} SCHEMA {json_path} AS {attribute} {type}
# NOTE: attribute = logical name,  json_path = JSONPath expressions

# example
> FT.CREATE userIdx ON JSON PREFIX 1 users: SCHEMA $.user.name AS name TEXT $.user.hobbies AS hobbies TAG $.user.age as age NUMERIC
# NOTE: You can search by any attribute mentioned in the above index for keys that start with users: (e.g. users:1).
  • 关于索引 JSON 的更多详细信息可以在 这里找到

索引创建后,任何现有/新增/修改的 JSON 文档都会自动被索引。

//sample json document
{
  "user": {
    "name": "John Smith",
    "hobbies": "foo,bar",
    "age": 23
  }
}
# adding JSON document
> JSON.SET myDoc $ '{"user":{"name":"John Smith","hobbies":"foo,bar","age":23}}'
  • 搜索
# search all user documents with name 'John'
> FT.SEARCH userIdx '@name:(John)'
1) (integer) 1
2) "myDoc"
3) 1) "$"
   2)  {"user":{"name":"John Smith","hobbies":"foo,bar","age":23}}"
  • 搜索与投影所需字段
# search documents with name 'John' & project only age field
> FT.SEARCH userIdx '@name:(John)' RETURN 1 $.user.age
1) (integer) 1
2) "myDoc"
3) 1) "$.user.age"
   2) "23"
# project multiple fields
> FT.SEARCH userIdx '@name:(John)' RETURN 2 $.user.age $.user.name
1) (integer) 1
2) "myDoc"
3) 1) "$.user.age"
   2) "23"
   3) "$.user.name"
   4) "John Smith"

#------------
# project with alias name
> FT.SEARCH userIdx '@name:(John)' RETURN 3 $.user.age AS userAge

1) (integer) 1
2) "myDoc"
3) 1) "userAge"
   2) "23"
#------------

# multi field query
> FT.SEARCH userIdx '@name:(John) @hobbies:{foo | me} @age:[20 30]'
1) (integer) 1
2) "myDoc"
3) 1) "$"
   2)  {"user":{"name":"John Smith","hobbies":"foo,bar","age":23}}"

关于 查询语法 的更多详细信息

  • 删除索引
> FT.DROPINDEX userIdx

有用资源

使用 Redis 进行概率数据和查询#

Redis Stack 支持概率数据类型和查询。下面是一个股票排行榜示例:

# Reserve a new leaderboard filter
> TOPK.RESERVE trending-stocks 12 50 4 0.9
"OK"

# Add a new entries to the leaderboard
> TOPK.ADD trending-stocks AAPL AMD MSFT INTC GOOG FB NFLX GME AMC TSLA
1) "null" ...

# Get the leaderboard
> TOPK.LIST trending-stocks
1) "AAPL"
2) "AMD"
2) "MSFT" ...

# Get information about the leaderboard
> TOPK.INFO trending-stocks
1) "k"
2) "12"
3) "width"
4) "50"
5) "depth"
6) "4"
7) "decay"
8) "0.90000000000000002"

更多详细信息请参阅 文档

使用 Redis 进行时间序列数据和查询#

Redis Stack 支持时间序列用例,例如物联网、股票价格和遥测数据。你可以以 Redis 的速度摄取和查询数百万个样本和事件。你还可以使用各种查询进行可视化和监控,并通过内置连接器连接到 Grafana、Prometheus 和 Telegraf 等流行工具。

以下示例演示了如何在 Redis Stack 中存储温度传感器读数:

# Create new time-series, for example temperature readings
> TS.CREATE temperature:raw DUPLICATE_POLICY LAST
"OK"

# Create a bucket for monthly aggregation
> TS.CREATE temperature:monthly DUPLICATE_POLICY LAST
"OK"

# Automatically aggregate based on time-weighted average
> TS.CREATERULE temperature:raw temperature:monthly AGGREGATION twa 2629800000
"OK"

# Add data to the raw time-series
> TS.MADD temperature:raw 1621666800000 52 ...
1) "1621666800000" ...

# View the monthly time-weighted average temperatures
> TS.RANGE temperature:monthly 0 +
1) 1) "1621666800000"
   2) "52" ...

# Delete compaction rule
> TS.DELETERULE temperature:raw temperature:monthly
"OK"

# Delete partial time-series
> TS.DEL temperature:raw 0 1621666800000
(integer) 1

更多详细信息请参阅 文档

附加资源#

最后更新于 2024 年 8 月 20 日