search
HomeDatabaseRedisHow to use the special data types of Redis

    1. HyperLogLog cardinality statistics

    1.1 What is cardinality?

    We can understand what cardinality statistics are directly through an example, such as the data set {1, 2, 3, 3, 5, 5,}, then the cardinality set of this data set is {1,2, 3, 5}, the base (non-repeating elements) is 4. That is to say, it is the number of non-repeating elements.

    1.2 Benefits of using cardinality statistics

    Each HyperLogLog key only requires 12 KB of memory to calculate the cardinality of close to 2^64 different elements. This is in sharp contrast to a collection that consumes more memory when calculating cardinality. The more elements there are, the more memory is consumed. If you want to compare from a memory perspective, Hyperloglog is the first choice.

    1.3 Application scenarios

    uv of web pages (a person visits a website multiple times, but is still counted as one person)

    • Traditional method: set (because set does not allow repetition, if repeated, it will be overwritten) saves the user's ID, and then statistics can be made. The number of elements in the set is used as a standard judgment. This method will be more troublesome if a large number of user IDs are saved and will be used in large websites. Takes up a lot of memory. Our purpose is to count, not to save user IDs.

    • Using HyperLogLog: A HyperLogLog key only requires 12KB, but the number that can be calculated is very huge, and the memory space occupied is greatly reduced.

    1.4 Notes

    If fault tolerance is allowed (0.81% error rate, it can be ignored when counting), then Hyperloglog can definitely be used! If fault tolerance is not allowed, just use set or your own data type!

    1.5 Basic commands

    Serial number Command and description
    1 PFADD key element [element ...]
    Add the specified element to HyperLogLog.
    2 PFCOUNT key [key ...]
    Returns the cardinality estimate for the given HyperLogLog.
    3 PFMERGE destkey sourcekey [sourcekey ...]
    Merge multiple HyperLogLogs into one HyperLogLog

    1.6 Using

    127.0.0.1:6379> pfadd mykey1 a b c d e f   #给第一组添加数据
    (integer) 1
    127.0.0.1:6379> pfcount mykey1  #统计mykey1的基数数量
    (integer) 6
    127.0.0.1:6379> pfadd mykey2 e e f j  #给第二组添加数据
    (integer) 1
    127.0.0.1:6379> pfcount mykey2     #统计mykey2的基数数量
    (integer) 3
    127.0.0.1:6379> pfmerge mykey3 mykey1 mykey2   # 合并两组 mykey1 mykey2 => mykey3 并集
    OK
    127.0.0.1:6379> pfcount mykey3    #统计mykey3的基数数量
    (integer) 7

    2. Geospatial geographical location

    2.1 Introduction

    Geospatial, which has been launched since version 3.2 of Redis, can calculate geographical location information between two places The distance between people, how many miles around.

    2.2 Usage scenarios

    • ???? Friend location

    • ???? View nearby people

    • ???? Taxi distance calculation

    2.3 Basic commands

    Serial number Commands and descriptions
    1 GEOADD key longitude latitude location name
    The specified geographical spatial location (latitude, longitude , name) is added to the specified key
    2 GEOPOS key location name
    Returns all the given location elements from the key location (latitude and longitude).
    3 GEODIST key location 1 location 2 unit
    Returns the distance between two given locations, if two locations If one of them does not exist, the command returns a null value.
    4

    GEORADIUS key Longitude and latitude range numerical unit

    With the given longitude and latitude as the center, find Out of elements within a certain radius

    5 GEORADIUSBYMEMBER key Location distance value unit
    Find out the elements within the specified range element, the center point is determined by the given position element
    6 GEOHASH key Location 1 Location 2
    will return 11 A Geohash string of characters. The closer the two strings are, the closer the distance is.
    7 zrange key start stop
    Get the coordinate information in the specified key
    8 zrem key location
    Delete the data of the specified target under the specified key

    查询地点经纬度:

    城市经纬度查询-国内城市经度纬度在线查询工具

    2.4 详细讲解

    2.4.1 GEOADD

    作用:添加地理位置

    规则:两级无法直接添加,我们一般会下载城市数据,直接通过java程序一次性导入!

    语法:GEOADD key 经度 纬度 地点名称

    注意事项

    有效的经度从-180度到180度。

    有效的纬度从-85.05112878度到85.05112878度。

    当坐标位置超出上述指定范围时,该命令将会返回一个错误。

    使用

    #添加单个信息
    127.0.0.1:6379> geoadd address 116.708463 23.37102 shantou   
    (integer) 1
    #添加多个信息
    127.0.0.1:6379> geoadd address 116.405285 39.904989 beijin 121.472644 31.231706 shanghai
    (integer) 2
    2.4.2 GEOPOS

    作用:获得指定地点的位置信息(经纬度)

    语法:GEOPOS key 地点名称

    使用

    127.0.0.1:6379> geopos address beijin   #获得北京的地理位置
    1) 1) "116.40528291463851929"  #经度
       2) "39.9049884229125027"   #纬度
    2.4.3 GEODIST

    作用:返回两个给定位置之间的距离,如果两个位置之间的其中一个不存在, 那么命令返回空值。

    语法:GEODIST key 地点1 地点2 单位

    单位参数:

    • m 表示单位为米。

    • km 表示单位为千米。

    • mi 表示单位为英里。

    • ft 表示单位为英尺。

    如果用户没有显式地指定单位参数, 那么 GEODIST 默认使用米作为单位。

    使用:

    127.0.0.1:6379> geodist address beijin shanghai km  #查询北京与上海之间的距离
    "1067.5980"
    2.4.4 GEORADIUS

    作用:以给定的经纬度为中心, 找出某一半径内的元素。

    语法:GEORADIUS key 经度 纬度  范围数值  单位

    使用:

    #查找以116,39这个经纬度为中心,寻找方圆1500km的城市
    127.0.0.1:6379> georadius address 116 39 1500 km
    1) "shanghai"
    2) "beijin"
     
    # 显示到中间距离的位置
    127.0.0.1:6379> georadius address 116 39 1500 km withdist
    1) 1) "shanghai"
       2) "996.7313"
    2) 1) "beijin"
       2) "106.5063"
     
    #显示他人的定位信息
    127.0.0.1:6379> georadius address 116 39 1500 km withcoord
    1) 1) "shanghai"
       2) 1) "121.47264629602432251"
          2) "31.23170490709807012"
    2) 1) "beijin"
       2) 1) "116.40528291463851929"
          2) "39.9049884229125027"
     
    #筛选出最近的城市以及显示其距离
    127.0.0.1:6379> georadius address 116 39 1500 km withdist withcoord count 1
    1) 1) "beijin"
       2) "106.5063"
       3) 1) "116.40528291463851929"
          2) "39.9049884229125027"
     
     
    #筛选最近两个城市以及显示其距离
    127.0.0.1:6379> georadius address 116 39 1500 km withdist withcoord count 2
    1) 1) "beijin"
       2) "106.5063"
       3) 1) "116.40528291463851929"
          2) "39.9049884229125027"
    2) 1) "shanghai"
       2) "996.7313"
       3) 1) "121.47264629602432251"
          2) "31.23170490709807012"
    2.4.5 GEORADIUSBYMEMBER

    作用:找出位于指定范围内的元素,中心点是由给定的位置元素决定。

    语法:GEORADIUSBYMEMBER  key 地点  距离数值  单位

    使用:

    #找出距离北京方圆1500km内的城市
    127.0.0.1:6379> georadiusbymember address beijin 1500 km
    1) "shanghai"
    2) "beijin"
    2.4.6 GEOHASH

    作用:将返回11个字符的Geohash字符串,如果两个字符串越接近,那么则距离越近。

    语法:GEOHASH  key 地点1  地点2

    ???? 使用:

    127.0.0.1:6379> geohash address beijin shantou
    1) "wx4g0b7xrt0"
    2) "ws4uzy8d030"
    2.4.7 ZRANGE

    作用:获得指定key中坐标信息。

    语法:zrange  key  start stop

    使用:

    127.0.0.1:6379> zrange address 0 -1
    1) "shantou"
    2) "shanghai"
    3) "beijin"
    2.4.8 ZREM

    作用:删除指定key下指定目标的数据。

    语法:zrem  key 地点

    使用:

    127.0.0.1:6379> zrem address shanghai
    (integer) 1

    三、BitMap

    介绍

    BitMap是通过一个bit位来表示某个元素对应的值或者状态,只有0 和 1 两个状态,其中的key就是对应元素本身。365 天 = 365 bit ,1字节 = 8bit ,也就是说统计一年的用户状态只需要46 个字节左右,所以其能够节省很大的空间。

    应用场景

    • (1)用户签到

    • (2)统计活跃用户

    • (3)用户在线状态(在线就设置为1,不在线就设置为0)

    使用

    • 需求:记录 周一到周日的打卡

    • 1:表示有打卡

    • 0:表示没有打卡

    127.0.0.1:6379> setbit sign 0 1
    (integer) 0
    127.0.0.1:6379> setbit sign 1 1
    (integer) 0
    127.0.0.1:6379> setbit sign 2 0
    (integer) 0
    127.0.0.1:6379> setbit sign 3 1
    (integer) 0
    127.0.0.1:6379> setbit sign 4 1
    (integer) 0
    127.0.0.1:6379> setbit sign 5 0
    (integer) 0
    127.0.0.1:6379> setbit sign 6 0
    (integer) 0

    查看某一天是否有打卡

    127.0.0.1:6379> getbit sign 3
    (integer) 1
    127.0.0.1:6379> getbit sign 6
    (integer) 0

    统计本周的打卡记录

    127.0.0.1:6379> bitcount sign
    (integer) 4

    The above is the detailed content of How to use the special data types of Redis. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    Redis: Understanding Its Architecture and PurposeRedis: Understanding Its Architecture and PurposeApr 26, 2025 am 12:11 AM

    Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

    Redis vs. SQL Databases: Key DifferencesRedis vs. SQL Databases: Key DifferencesApr 25, 2025 am 12:02 AM

    The main difference between Redis and SQL databases is that Redis is an in-memory database, suitable for high performance and flexibility requirements; SQL database is a relational database, suitable for complex queries and data consistency requirements. Specifically, 1) Redis provides high-speed data access and caching services, supports multiple data types, suitable for caching and real-time data processing; 2) SQL database manages data through a table structure, supports complex queries and transaction processing, and is suitable for scenarios such as e-commerce and financial systems that require data consistency.

    Redis: How It Acts as a Data Store and ServiceRedis: How It Acts as a Data Store and ServiceApr 24, 2025 am 12:08 AM

    Redisactsasbothadatastoreandaservice.1)Asadatastore,itusesin-memorystorageforfastoperations,supportingvariousdatastructureslikekey-valuepairsandsortedsets.2)Asaservice,itprovidesfunctionalitieslikepub/submessagingandLuascriptingforcomplexoperationsan

    Redis vs. Other Databases: A Comparative AnalysisRedis vs. Other Databases: A Comparative AnalysisApr 23, 2025 am 12:16 AM

    Compared with other databases, Redis has the following unique advantages: 1) extremely fast speed, and read and write operations are usually at the microsecond level; 2) supports rich data structures and operations; 3) flexible usage scenarios such as caches, counters and publish subscriptions. When choosing Redis or other databases, it depends on the specific needs and scenarios. Redis performs well in high-performance and low-latency applications.

    Redis's Role: Exploring the Data Storage and Management CapabilitiesRedis's Role: Exploring the Data Storage and Management CapabilitiesApr 22, 2025 am 12:10 AM

    Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

    Redis: Understanding NoSQL ConceptsRedis: Understanding NoSQL ConceptsApr 21, 2025 am 12:04 AM

    Redis is a NoSQL database suitable for efficient storage and access of large-scale data. 1.Redis is an open source memory data structure storage system that supports multiple data structures. 2. It provides extremely fast read and write speeds, suitable for caching, session management, etc. 3.Redis supports persistence and ensures data security through RDB and AOF. 4. Usage examples include basic key-value pair operations and advanced collection deduplication functions. 5. Common errors include connection problems, data type mismatch and memory overflow, so you need to pay attention to debugging. 6. Performance optimization suggestions include selecting the appropriate data structure and setting up memory elimination strategies.

    Redis: Real-World Use Cases and ExamplesRedis: Real-World Use Cases and ExamplesApr 20, 2025 am 12:06 AM

    The applications of Redis in the real world include: 1. As a cache system, accelerate database query, 2. To store the session data of web applications, 3. To implement real-time rankings, 4. To simplify message delivery as a message queue. Redis's versatility and high performance make it shine in these scenarios.

    Redis: Exploring Its Features and FunctionalityRedis: Exploring Its Features and FunctionalityApr 19, 2025 am 12:04 AM

    Redis stands out because of its high speed, versatility and rich data structure. 1) Redis supports data structures such as strings, lists, collections, hashs and ordered collections. 2) It stores data through memory and supports RDB and AOF persistence. 3) Starting from Redis 6.0, multi-threaded I/O operations have been introduced, which has improved performance in high concurrency scenarios.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    EditPlus Chinese cracked version

    EditPlus Chinese cracked version

    Small size, syntax highlighting, does not support code prompt function

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.