One place for hosting & domains

      Hashes

      Como Gerenciar Hashes no Redis


      Introdução

      O Redis é um datastore ou armazenamento de dados open-source de chave-valor na memória. Um hash do Redis é um tipo de dado que representa um mapeamento entre um campo de string e um valor de string. Os hashes podem conter muitos pares de campo-valor e são projetados para não ocupar muito espaço, tornando-os ideais para representar objetos de dados. Por exemplo, um hash pode representar um cliente e incluir campos como nome, endereço, e-mail ou cliente_id.

      Este tutorial abordará como gerenciar hashes no Redis, desde a criação deles até a recuperação e exclusão dos dados mantidos em um hash.

      Como Utilizar Este Guia

      Este guia está no formato de referência rápida com trechos de linha de comando independentes. Recomendamos que você pule para qualquer seção que seja relevante para a tarefa que você está tentando concluir.

      Os comandos mostrados neste guia foram testados em um servidor Ubuntu 18.04 executando a versão 4.0.9 do Redis. Para configurar um ambiente semelhante, você pode seguir o Passo 1 do nosso guia Como Instalar e Proteger o Redis no Ubuntu 18.04. Vamos demonstrar como esses comandos se comportam executando-os com redis-cli, a interface de linha de comando do Redis. Observe que se você estiver usando uma interface Redis diferente — Redli, por exemplo — a saída exata de certos comandos pode ser diferente.

      Como alternativa, você pode provisionar uma instância de banco de dados Redis gerenciada para testar esses comandos, mas observe que, dependendo do nível de controle permitido pelo seu provedor de banco de dados, alguns comandos neste guia podem não funcionar como descrito. Para provisionar um banco de dados gerenciado na DigitalOcean, siga nossa documentação de produto para Managed Databases. Então, você deve instalar ou o Redli ou configurar um túnel TLS para conectar-se ao banco de dados gerenciado por TLS.

      Criando Hashes

      Para criar um hash, execute o comando hset. Este comando aceita o nome da chave do hash, o campo de string e o valor correspondente da string como argumentos:

      • hset poet:Verlaine nationality French

      Nota: Neste exemplo e nos seguintes, poet:Verlaine é a chave do hash. Pontos, traços e dois-pontos são comumente usados para tornar as chaves e campos com várias palavras mais legíveis. É útil garantir que suas chaves sigam um formato consistente e de fácil leitura.

      O hset retorna (integer) 1 se o campo especificado for um novo campo e o valor tiver sido corretamente definido:

      Output

      (integer) 1

      Se, no entanto, você não incluir um valor, campo ou nome para a chave do hash, o hset retornará um erro.

      Além disso, observe que o hset substituirá o conteúdo do hash se ele já existir:

      • hset poet:Verlaine nationality Francais

      Se o campo já existe e seu valor foi atualizado com sucesso, o hset retornará (integer) 0:

      Output

      (integer) 0

      Você também pode usar o hsetnx para adicionar campos aos hashes, mas ele só funcionará se o campo ainda não existir. Se o campo especificado já existir, o hsetnx não terá nenhum efeito e retornará (integer) 0:

      • hsetnx poet:Verlaine nationality French

      Output

      (integer) 0

      Para definir vários pares de campo/valor para um determinado conjunto, use o comando hmset seguido pelas strings de campo/valor correspondentes:

      • hmset poet:Verlaine born 1844 died 1896 genre Decadent

      O hmset retornará apenas OK se tiver sido executado com sucesso.

      Recuperando Informações dos Hashes

      Você pode determinar se existe um campo para um determinado hash com o comando hexists:

      • hexists poet:Verlaine nationality

      O hexists retornará (integer) 1 se o campo existir, e (integer) 0 se não existir.

      Para retornar o valor de um campo, execute o comando hget seguido da chave do hash e do campo cujo valor você deseja recuperar:

      • hget poet:Verlaine nationality

      Output

      "Francais"

      O hmget usa a mesma sintaxe, mas pode retornar os valores de vários campos.

      • hmget poet:Verlaine born died

      Output

      1) "1844" 2) "1896"

      Se o hash que você passar para hget ou para o hmget não existir, os dois comandos retornarão (nil):

      • hmget poet:Dickinson born died

      Output

      1) (nil) 2) (nil)

      Para obter uma lista de todos os campos mantidos em um determinado hash, execute o comando hkeys:

      Output

      1) "nationality" 2) "born" 3) "died" 4) "genre"

      Por outro lado, execute hvals para recuperar uma lista de valores mantidos dentro de um hash:

      Output

      1) "French" 2) "1844" 3) "1896" 4) "Decadent"

      Para retornar uma lista de todos os campos mantidos por um hash e seus valores associados, execute o hgetall:

      Output

      1) "nationality" 2) "French" 3) "born" 4) "1844" 5) "died" 6) "1896" 7) "genre" 8) "Decadent"

      Você pode encontrar o número de campos em um hash executando o hlen, que significa “hash length” ou comprimento do hash:

      Output

      (integer) 4

      Você pode encontrar o comprimento da string de valor associada a um campo com o hstrlen, que significa “hash string length” ou comprimento da string do hash:

      • hstrlen poet:Verlaine nationality

      Output

      (integer) 8

      O hlen retornará (integer) 0 se o hash não existir.

      Removendo Campos dos Hashes

      Para excluir um campo de um hash, execute o comando hdel. O hdel pode aceitar vários campos como argumentos e retornará um número inteiro indicando quantos campos foram removidos do hash:

      • hdel poet:Verlaine born died

      Output

      (integer) 2

      Se você passar um campo que não existe para o hdel, ele irá ignorar esse campo, mas excluirá quaisquer outros campos existentes que você especificar.

      Conclusão

      Este guia detalha vários comandos usados para criar e gerenciar hashes no Redis. Se houver outros comandos, argumentos ou procedimentos relacionados que você gostaria de ver descritos neste guia, peça ou faça sugestões nos comentários abaixo.

      Para obter mais informações sobre comandos Redis, consulte nossa série de tutoriais Como Gerenciar um Banco de Dados Redis.



      Source link

      How To Manage Hashes in Redis


      Introduction

      Redis is an open-source, in-memory key-value data store. A Redis hash is a data type that represents a mapping between a string field and a string value. Hashes can hold many field-value pairs and are designed to not take up much space, making them ideal for representing data objects. For example, a hash might represent a customer, and include fields like name, address, email, or customer_id.

      This tutorial will go over how to manage hashes in Redis, from creating them to retrieving and deleting the data held within a hash.

      How To Use This Guide
      This guide is written as a cheat sheet with self-contained examples. We encourage you to jump to any section that is relevant to the task you’re trying to complete.

      The commands and outputs shown in this guide were tested on an Ubuntu 18.04 server running Redis version 4.0.9. To obtain a similar setup, you can follow Step 1 of our guide on How To Install and Secure Redis on Ubuntu 18.04. We will demonstrate how these commands behave by running them with redis-cli, the Redis command line interface. Note that if you’re using a different Redis interface — Redli, for example — the exact outputs of certain commands may differ.

      Alternatively, you could provision a managed Redis database instance to test these commands, but note that depending on the level of control allowed by your database provider, some commands in this guide may not work as described. To provision a DigitalOcean Managed Database, follow our Managed Databases product documentation. Then, you must either install Redli or set up a TLS tunnel in order to connect to the Managed Database over TLS.

      Creating Hashes

      To create a hash, run the hset command. This command accepts the name of the hash key, the field string, and corresponding value string as arguments:

      • hset poet:Verlaine nationality French

      Note: In this example and the following ones, poet:Verlaine is the hash key. Dots, dashes, and colons are commonly used to make multi-word keys and fields more readable. It’s helpful to make sure that your keys follow a consistent and easily readable format.

      hset returns (integer) 1 if the field specified is a new field and the value was set correctly:

      Output

      (integer) 1

      If, however, you fail to include a value, field, or name for the hash key, hset will return an error.

      Also, note that hset will overwrite the contents of the hash if it already exists:

      • hset poet:Verlaine nationality Francais

      If the field already exists and its value was updated successfully, hset will return (integer) 0:

      Output

      (integer) 0

      You can also use hsetnx to add fields to hashes, but it will only work if the field does not yet exist. If the specified field does already exist, the hsetnx won’t have any effect and will return (integer) 0:

      • hsetnx poet:Verlaine nationality French

      Output

      (integer) 0

      To set multiple field/value pairs to a given set, use the hmset command followed by the corresponding field/value strings:

      • hmset poet:Verlaine born 1844 died 1896 genre Decadent

      hmset will just return OK if it was successful.

      Retrieving Information from Hashes

      You can determine if a field exists for a given hash with the hexists command:

      • hexists poet:Verlaine nationality

      hexists will return (integer) 1 if the field does exist, and (integer) 0 if it doesn’t.

      To return a field’s value, run the hget command followed by the hash key and the field whose value you want to retrieve:

      • hget poet:Verlaine nationality

      Output

      "Francais"

      hmget uses the same syntax, but can return the values of multiple fields

      • hmget poet:Verlaine born died

      Output

      1) "1844" 2) "1896"

      If the hash you pass to hget or hmget does not exist, both commands will return (nil):

      • hmget poet:Dickinson born died

      Output

      1) (nil) 2) (nil)

      To obtain a list of all the fields held within a certain hash, run the hkeys command:

      Output

      1) "nationality" 2) "born" 3) "died" 4) "genre"

      Conversely, run hvals to retrieve a list of values held within a hash:

      Output

      1) "French" 2) "1844" 3) "1896" 4) "Decadent"

      To return a list of every field held by a hash and their associated values, run hgetall:

      Output

      1) "nationality" 2) "French" 3) "born" 4) "1844" 5) "died" 6) "1896" 7) "genre" 8) "Decadent"

      You can find the number of fields in a hash by running hlen, which stands for “hash length”:

      Output

      (integer) 4

      You can find the length of the value string associated with a field with hstrlen, which stands for “hash string length”:

      • hstrlen poet:Verlaine nationality

      Output

      (integer) 8

      hlen will return (integer) 0 if the hash does not exist.

      Removing Fields from Hashes

      To delete a field from a hash, run the hdel command. hdel can accept multiple fields as arguments, and will return an integer indicating how many fields were removed from the hash:

      • hdel poet:Verlaine born died

      Output

      (integer) 2

      If you pass a field that does not exist to hdel, it will ignore that field but delete any other existing fields you specify.

      Conclusion

      This guide details a number of commands used to create and manage hashes in Redis. If there are other related commands, arguments, or procedures you’d like to see outlined in this guide, please ask or make suggestions in the comments below.

      For more information on Redis commands, see our tutorial series on How to Manage a Redis Database.



      Source link