Giter Club home page Giter Club logo

redis-om-python's Introduction

This README is just a fast quick start document. You can find more detailed documentation at redis.io.

What is Redis?

Redis is often referred to as a data structures server. What this means is that Redis provides access to mutable data structures via a set of commands, which are sent using a server-client model with TCP sockets and a simple protocol. So different processes can query and modify the same data structures in a shared way.

Data structures implemented into Redis have a few special properties:

  • Redis cares to store them on disk, even if they are always served and modified into the server memory. This means that Redis is fast, but that it is also non-volatile.
  • The implementation of data structures emphasizes memory efficiency, so data structures inside Redis will likely use less memory compared to the same data structure modelled using a high-level programming language.
  • Redis offers a number of features that are natural to find in a database, like replication, tunable levels of durability, clustering, and high availability.

Another good example is to think of Redis as a more complex version of memcached, where the operations are not just SETs and GETs, but operations that work with complex data types like Lists, Sets, ordered data structures, and so forth.

If you want to know more, this is a list of selected starting points:

Building Redis

Redis can be compiled and used on Linux, OSX, OpenBSD, NetBSD, FreeBSD. We support big endian and little endian architectures, and both 32 bit and 64 bit systems.

It may compile on Solaris derived systems (for instance SmartOS) but our support for this platform is best effort and Redis is not guaranteed to work as well as in Linux, OSX, and *BSD.

It is as simple as:

% make

To build with TLS support, you'll need OpenSSL development libraries (e.g. libssl-dev on Debian/Ubuntu) and run:

% make BUILD_TLS=yes

To build with systemd support, you'll need systemd development libraries (such as libsystemd-dev on Debian/Ubuntu or systemd-devel on CentOS) and run:

% make USE_SYSTEMD=yes

To append a suffix to Redis program names, use:

% make PROG_SUFFIX="-alt"

You can build a 32 bit Redis binary using:

% make 32bit

After building Redis, it is a good idea to test it using:

% make test

If TLS is built, running the tests with TLS enabled (you will need tcl-tls installed):

% ./utils/gen-test-certs.sh
% ./runtest --tls

Fixing build problems with dependencies or cached build options

Redis has some dependencies which are included in the deps directory. make does not automatically rebuild dependencies even if something in the source code of dependencies changes.

When you update the source code with git pull or when code inside the dependencies tree is modified in any other way, make sure to use the following command in order to really clean everything and rebuild from scratch:

% make distclean

This will clean: jemalloc, lua, hiredis, linenoise and other dependencies.

Also if you force certain build options like 32bit target, no C compiler optimizations (for debugging purposes), and other similar build time options, those options are cached indefinitely until you issue a make distclean command.

Fixing problems building 32 bit binaries

If after building Redis with a 32 bit target you need to rebuild it with a 64 bit target, or the other way around, you need to perform a make distclean in the root directory of the Redis distribution.

In case of build errors when trying to build a 32 bit binary of Redis, try the following steps:

  • Install the package libc6-dev-i386 (also try g++-multilib).
  • Try using the following command line instead of make 32bit: make CFLAGS="-m32 -march=native" LDFLAGS="-m32"

Allocator

Selecting a non-default memory allocator when building Redis is done by setting the MALLOC environment variable. Redis is compiled and linked against libc malloc by default, with the exception of jemalloc being the default on Linux systems. This default was picked because jemalloc has proven to have fewer fragmentation problems than libc malloc.

To force compiling against libc malloc, use:

% make MALLOC=libc

To compile against jemalloc on Mac OS X systems, use:

% make MALLOC=jemalloc

Monotonic clock

By default, Redis will build using the POSIX clock_gettime function as the monotonic clock source. On most modern systems, the internal processor clock can be used to improve performance. Cautions can be found here: http://oliveryang.net/2015/09/pitfalls-of-TSC-usage/

To build with support for the processor's internal instruction clock, use:

% make CFLAGS="-DUSE_PROCESSOR_CLOCK"

Verbose build

Redis will build with a user-friendly colorized output by default. If you want to see a more verbose output, use the following:

% make V=1

Running Redis

To run Redis with the default configuration, just type:

% cd src
% ./redis-server

If you want to provide your redis.conf, you have to run it using an additional parameter (the path of the configuration file):

% cd src
% ./redis-server /path/to/redis.conf

It is possible to alter the Redis configuration by passing parameters directly as options using the command line. Examples:

% ./redis-server --port 9999 --replicaof 127.0.0.1 6379
% ./redis-server /etc/redis/6379.conf --loglevel debug

All the options in redis.conf are also supported as options using the command line, with exactly the same name.

Running Redis with TLS:

Please consult the TLS.md file for more information on how to use Redis with TLS.

Playing with Redis

You can use redis-cli to play with Redis. Start a redis-server instance, then in another terminal try the following:

% cd src
% ./redis-cli
redis> ping
PONG
redis> set foo bar
OK
redis> get foo
"bar"
redis> incr mycounter
(integer) 1
redis> incr mycounter
(integer) 2
redis>

You can find the list of all the available commands at https://redis.io/commands.

Installing Redis

In order to install Redis binaries into /usr/local/bin, just use:

% make install

You can use make PREFIX=/some/other/directory install if you wish to use a different destination.

make install will just install binaries in your system, but will not configure init scripts and configuration files in the appropriate place. This is not needed if you just want to play a bit with Redis, but if you are installing it the proper way for a production system, we have a script that does this for Ubuntu and Debian systems:

% cd utils
% ./install_server.sh

Note: install_server.sh will not work on Mac OSX; it is built for Linux only.

The script will ask you a few questions and will setup everything you need to run Redis properly as a background daemon that will start again on system reboots.

You'll be able to stop and start Redis using the script named /etc/init.d/redis_<portnumber>, for instance /etc/init.d/redis_6379.

Code contributions

By contributing code to the Redis project in any form, including sending a pull request via GitHub, a code fragment or patch via private email or public discussion groups, you agree to release your code under the terms of the Redis Software Grant and Contributor License Agreement. Redis software contains contributions to the original Redis core project, which are owned by their contributors and licensed under the 3BSD license. Any copy of that license in this repository applies only to those contributions. Redis releases all Redis project versions from 7.4.x and thereafter under the RSALv2/SSPL dual-license as described in the LICENSE.txt file included in the Redis source distribution.

Please see the CONTRIBUTING.md file in this source distribution for more information. For security bugs and vulnerabilities, please see SECURITY.md.

Redis Trademarks

The purpose of a trademark is to identify the goods and services of a person or company without causing confusion. As the registered owner of its name and logo, Redis accepts certain limited uses of its trademarks but it has requirements that must be followed as described in its Trademark Guidelines available at: https://redis.com/legal/trademark-guidelines/.

Redis internals

If you are reading this README you are likely in front of a Github page or you just untarred the Redis distribution tar ball. In both the cases you are basically one step away from the source code, so here we explain the Redis source code layout, what is in each file as a general idea, the most important functions and structures inside the Redis server and so forth. We keep all the discussion at a high level without digging into the details since this document would be huge otherwise and our code base changes continuously, but a general idea should be a good starting point to understand more. Moreover most of the code is heavily commented and easy to follow.

Source code layout

The Redis root directory just contains this README, the Makefile which calls the real Makefile inside the src directory and an example configuration for Redis and Sentinel. You can find a few shell scripts that are used in order to execute the Redis, Redis Cluster and Redis Sentinel unit tests, which are implemented inside the tests directory.

Inside the root are the following important directories:

  • src: contains the Redis implementation, written in C.
  • tests: contains the unit tests, implemented in Tcl.
  • deps: contains libraries Redis uses. Everything needed to compile Redis is inside this directory; your system just needs to provide libc, a POSIX compatible interface and a C compiler. Notably deps contains a copy of jemalloc, which is the default allocator of Redis under Linux. Note that under deps there are also things which started with the Redis project, but for which the main repository is not redis/redis.

There are a few more directories but they are not very important for our goals here. We'll focus mostly on src, where the Redis implementation is contained, exploring what there is inside each file. The order in which files are exposed is the logical one to follow in order to disclose different layers of complexity incrementally.

Note: lately Redis was refactored quite a bit. Function names and file names have been changed, so you may find that this documentation reflects the unstable branch more closely. For instance, in Redis 3.0 the server.c and server.h files were named redis.c and redis.h. However the overall structure is the same. Keep in mind that all the new developments and pull requests should be performed against the unstable branch.

server.h

The simplest way to understand how a program works is to understand the data structures it uses. So we'll start from the main header file of Redis, which is server.h.

All the server configuration and in general all the shared state is defined in a global structure called server, of type struct redisServer. A few important fields in this structure are:

  • server.db is an array of Redis databases, where data is stored.
  • server.commands is the command table.
  • server.clients is a linked list of clients connected to the server.
  • server.master is a special client, the master, if the instance is a replica.

There are tons of other fields. Most fields are commented directly inside the structure definition.

Another important Redis data structure is the one defining a client. In the past it was called redisClient, now just client. The structure has many fields, here we'll just show the main ones:

struct client {
    int fd;
    sds querybuf;
    int argc;
    robj **argv;
    redisDb *db;
    int flags;
    list *reply;
    // ... many other fields ...
    char buf[PROTO_REPLY_CHUNK_BYTES];
}

The client structure defines a connected client:

  • The fd field is the client socket file descriptor.
  • argc and argv are populated with the command the client is executing, so that functions implementing a given Redis command can read the arguments.
  • querybuf accumulates the requests from the client, which are parsed by the Redis server according to the Redis protocol and executed by calling the implementations of the commands the client is executing.
  • reply and buf are dynamic and static buffers that accumulate the replies the server sends to the client. These buffers are incrementally written to the socket as soon as the file descriptor is writable.

As you can see in the client structure above, arguments in a command are described as robj structures. The following is the full robj structure, which defines a Redis object:

struct redisObject {
    unsigned type:4;
    unsigned encoding:4;
    unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
                            * LFU data (least significant 8 bits frequency
                            * and most significant 16 bits access time). */
    int refcount;
    void *ptr;
};

Basically this structure can represent all the basic Redis data types like strings, lists, sets, sorted sets and so forth. The interesting thing is that it has a type field, so that it is possible to know what type a given object has, and a refcount, so that the same object can be referenced in multiple places without allocating it multiple times. Finally the ptr field points to the actual representation of the object, which might vary even for the same type, depending on the encoding used.

Redis objects are used extensively in the Redis internals, however in order to avoid the overhead of indirect accesses, recently in many places we just use plain dynamic strings not wrapped inside a Redis object.

server.c

This is the entry point of the Redis server, where the main() function is defined. The following are the most important steps in order to startup the Redis server.

  • initServerConfig() sets up the default values of the server structure.
  • initServer() allocates the data structures needed to operate, setup the listening socket, and so forth.
  • aeMain() starts the event loop which listens for new connections.

There are two special functions called periodically by the event loop:

  1. serverCron() is called periodically (according to server.hz frequency), and performs tasks that must be performed from time to time, like checking for timed out clients.
  2. beforeSleep() is called every time the event loop fired, Redis served a few requests, and is returning back into the event loop.

Inside server.c you can find code that handles other vital things of the Redis server:

  • call() is used in order to call a given command in the context of a given client.
  • activeExpireCycle() handles eviction of keys with a time to live set via the EXPIRE command.
  • performEvictions() is called when a new write command should be performed but Redis is out of memory according to the maxmemory directive.
  • The global variable redisCommandTable defines all the Redis commands, specifying the name of the command, the function implementing the command, the number of arguments required, and other properties of each command.

commands.c

This file is auto generated by utils/generate-command-code.py, the content is based on the JSON files in the src/commands folder. These are meant to be the single source of truth about the Redis commands, and all the metadata about them. These JSON files are not meant to be used by anyone directly, instead that metadata can be obtained via the COMMAND command.

networking.c

This file defines all the I/O functions with clients, masters and replicas (which in Redis are just special clients):

  • createClient() allocates and initializes a new client.
  • The addReply*() family of functions are used by command implementations in order to append data to the client structure, that will be transmitted to the client as a reply for a given command executed.
  • writeToClient() transmits the data pending in the output buffers to the client and is called by the writable event handler sendReplyToClient().
  • readQueryFromClient() is the readable event handler and accumulates data read from the client into the query buffer.
  • processInputBuffer() is the entry point in order to parse the client query buffer according to the Redis protocol. Once commands are ready to be processed, it calls processCommand() which is defined inside server.c in order to actually execute the command.
  • freeClient() deallocates, disconnects and removes a client.

aof.c and rdb.c

As you can guess from the names, these files implement the RDB and AOF persistence for Redis. Redis uses a persistence model based on the fork() system call in order to create a process with the same (shared) memory content of the main Redis process. This secondary process dumps the content of the memory on disk. This is used by rdb.c to create the snapshots on disk and by aof.c in order to perform the AOF rewrite when the append only file gets too big.

The implementation inside aof.c has additional functions in order to implement an API that allows commands to append new commands into the AOF file as clients execute them.

The call() function defined inside server.c is responsible for calling the functions that in turn will write the commands into the AOF.

db.c

Certain Redis commands operate on specific data types; others are general. Examples of generic commands are DEL and EXPIRE. They operate on keys and not on their values specifically. All those generic commands are defined inside db.c.

Moreover db.c implements an API in order to perform certain operations on the Redis dataset without directly accessing the internal data structures.

The most important functions inside db.c which are used in many command implementations are the following:

  • lookupKeyRead() and lookupKeyWrite() are used in order to get a pointer to the value associated to a given key, or NULL if the key does not exist.
  • dbAdd() and its higher level counterpart setKey() create a new key in a Redis database.
  • dbDelete() removes a key and its associated value.
  • emptyData() removes an entire single database or all the databases defined.

The rest of the file implements the generic commands exposed to the client.

object.c

The robj structure defining Redis objects was already described. Inside object.c there are all the functions that operate with Redis objects at a basic level, like functions to allocate new objects, handle the reference counting and so forth. Notable functions inside this file:

  • incrRefCount() and decrRefCount() are used in order to increment or decrement an object reference count. When it drops to 0 the object is finally freed.
  • createObject() allocates a new object. There are also specialized functions to allocate string objects having a specific content, like createStringObjectFromLongLong() and similar functions.

This file also implements the OBJECT command.

replication.c

This is one of the most complex files inside Redis, it is recommended to approach it only after getting a bit familiar with the rest of the code base. In this file there is the implementation of both the master and replica role of Redis.

One of the most important functions inside this file is replicationFeedSlaves() that writes commands to the clients representing replica instances connected to our master, so that the replicas can get the writes performed by the clients: this way their data set will remain synchronized with the one in the master.

This file also implements both the SYNC and PSYNC commands that are used in order to perform the first synchronization between masters and replicas, or to continue the replication after a disconnection.

Script

The script unit is composed of 3 units:

  • script.c - integration of scripts with Redis (commands execution, set replication/resp, ...)
  • script_lua.c - responsible to execute Lua code, uses script.c to interact with Redis from within the Lua code.
  • function_lua.c - contains the Lua engine implementation, uses script_lua.c to execute the Lua code.
  • functions.c - contains Redis Functions implementation (FUNCTION command), uses functions_lua.c if the function it wants to invoke needs the Lua engine.
  • eval.c - contains the eval implementation using script_lua.c to invoke the Lua code.

Other C files

  • t_hash.c, t_list.c, t_set.c, t_string.c, t_zset.c and t_stream.c contains the implementation of the Redis data types. They implement both an API to access a given data type, and the client command implementations for these data types.
  • ae.c implements the Redis event loop, it's a self contained library which is simple to read and understand.
  • sds.c is the Redis string library, check https://github.com/antirez/sds for more information.
  • anet.c is a library to use POSIX networking in a simpler way compared to the raw interface exposed by the kernel.
  • dict.c is an implementation of a non-blocking hash table which rehashes incrementally.
  • cluster.c implements the Redis Cluster. Probably a good read only after being very familiar with the rest of the Redis code base. If you want to read cluster.c make sure to read the Redis Cluster specification.

Anatomy of a Redis command

All the Redis commands are defined in the following way:

void foobarCommand(client *c) {
    printf("%s",c->argv[1]->ptr); /* Do something with the argument. */
    addReply(c,shared.ok); /* Reply something to the client. */
}

The command function is referenced by a JSON file, together with its metadata, see commands.c described above for details. The command flags are documented in the comment above the struct redisCommand in server.h. For other details, please refer to the COMMAND command. https://redis.io/commands/command/

After the command operates in some way, it returns a reply to the client, usually using addReply() or a similar function defined inside networking.c.

There are tons of command implementations inside the Redis source code that can serve as examples of actual commands implementations (e.g. pingCommand). Writing a few toy commands can be a good exercise to get familiar with the code base.

There are also many other files not described here, but it is useless to cover everything. We just want to help you with the first steps. Eventually you'll find your way inside the Redis code base :-)

Enjoy!

redis-om-python's People

Contributors

bonastreyair avatar chayim avatar dependabot[bot] avatar dracco1993 avatar dvora-h avatar gaby avatar glxplz avatar marianhlavac avatar melder avatar mheguy-stingray avatar moznuy avatar ninoseki avatar pwuts avatar ryanrussell avatar simonprickett avatar slorello89 avatar tonibofarull avatar uglide avatar wiseaidev avatar yaraslauzhylko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

redis-om-python's Issues

RediSearch version < 2.2 with migrate there is no error message

Hello,

I know that, RediSearch version >= 2.2 support RedisJson.
When using redis-om with RediSearch version < 2.2 by mistake and running migrate. It did not give any error message, just there are no index. I spent some time to figure it out. if there is an error message it will be much easier to debug.

redis.exceptions.ResponseError: unknown command 'module'

Hi,

So basically trying to reproduce what @simonprickett did here except that i'm doing it on Redis cloud instead of locally or using a venv or docker or whatever.

So i've managed to successfully write to the redis db cloud after properly configuring REDIS_OM_URL to point at the proper endpoint x credentials, now when I perform a rediSearch query ex:
Adoptable.find(Adoptable.name == "Poppy").all()
I get the error
redis.exceptions.ResponseError: unknown command 'module'
Another way of reproducing the above is as follows:

from redis import ResponseError
try:
    Adoptable.find(Adoptable.name == "Poppy").all()
except ResponseError as e:
    print(e)

I've googled the above type of error but all i see is the same type of error but the word 'module' being swapped by different terms (ex: like JSON.GET whose solution was to include redisJSON)
Any help is appreciated, thank you.

PS: yes i have created my database by properly including modules rediSearch and redisJSON.

ahmad

Can't define `model_key_prefix` in base class.

Like describe in The Meta Object Is "Special", It's not possible to define meta field model_key_prefix in base model.

class BaseModel(HashModel, ABC):
    class Meta:
        model_key_prefix= "some-information"

class Customer(BaseModel):
    first_name: str
    last_name: str

Customer.model_key_prefix value is not set to "some-information" but, for example, __main__.Customer.

Indeed, I notice that in model.py#L1059, we have :

        if not getattr(new_class._meta, "model_key_prefix", None):
            # Don't look at the base class for this.
            new_class._meta.model_key_prefix = (
                f"{new_class.__module__}.{new_class.__name__}"
            )

It is then not possible to define model_key_prefix in base class.

Why is that?

Document toml file for FastAPI integraion

FastAPI integraion documentation says project could be used as is. But there is no toml file for this Poetry project.
I've created one via poetry init but there still need to be test attribute in main module. Without it, following command is not working properly

$ poetry run uvicorn --reload main:test

Getting following error on launch:

ERROR:    Error loading ASGI app. Attribute "test" not found in module "main".

When global_key_prefix empty, the model key start with :

When not provide global_key_prefix meta attribute or default, the Model's key looks like this:

:mymodule.User:01FW344MBY7AJJTB8H3HRD9J2X

Maybe should strip : start with?

    @classmethod
    def make_key(cls, part: str):
        global_prefix = getattr(cls._meta, "global_key_prefix", "").strip(":")
        model_prefix = getattr(cls._meta, "model_key_prefix", "").strip(":")
        return f"{global_prefix}:{model_prefix}:{part}"

Document model and field classes in depth

Document the model classes and field possibilities in-depth:

  • JsonModel
  • HashModel

Fields:

  • String fields
  • Date fields (no range queries yet!)
  • Numerical fields (these do support range queries)
  • Lists that become "tag" fields

This file should probably give more details about how this model interacts with RediSearch/RedisJSON schemas.

Document async vs. sync usage

Redis OM Python supports both async and sync usage. Async support is provided in the aredis_om module, which is otherwise identical to the synchronous code found in redis_om. Document this.

Failing to install. Cannot install hiredis

Collecting redis-om
  Using cached redis_om-0.0.20-py3-none-any.whl (74 kB)
Requirement already satisfied: redis<5.0.0,>=3.5.3 in c:\users\marsel\appdata\local\programs\python\python310\lib\site-packages (from redis-om) (4.1.4)
Collecting hiredis<3.0.0,>=2.0.0
  Using cached hiredis-2.0.0.tar.gz (75 kB)
  Preparing metadata (setup.py) ... done
Collecting python-dotenv<0.20.0,>=0.19.1
  Downloading python_dotenv-0.19.2-py2.py3-none-any.whl (17 kB)
Collecting click<9.0.0,>=8.0.1
  Using cached click-8.0.4-py3-none-any.whl (97 kB)
Collecting cleo==1.0.0a4
  Using cached cleo-1.0.0a4-py3-none-any.whl (77 kB)
Collecting types-six<2.0.0,>=1.16.1
  Using cached types_six-1.16.12-py3-none-any.whl (13 kB)
Collecting typing-extensions<5.0.0,>=4.0.0
  Using cached typing_extensions-4.1.1-py3-none-any.whl (26 kB)
Collecting pptree<4.0,>=3.1
  Using cached pptree-3.1.tar.gz (3.0 kB)
  Preparing metadata (setup.py) ... done
Collecting aioredis<3.0.0,>=2.0.0
  Using cached aioredis-2.0.1-py3-none-any.whl (71 kB)
Collecting python-ulid<2.0.0,>=1.0.3
  Using cached python_ulid-1.1.0-py3-none-any.whl (9.4 kB)
Collecting types-redis<5.0.0,>=3.5.9
  Using cached types_redis-4.1.17-py3-none-any.whl (34 kB)
Collecting six<2.0.0,>=1.16.0
  Using cached six-1.16.0-py2.py3-none-any.whl (11 kB)
Collecting pydantic<2.0.0,>=1.8.2
  Using cached pydantic-1.9.0-cp310-cp310-win_amd64.whl (2.1 MB)
Collecting crashtest<0.4.0,>=0.3.1
  Using cached crashtest-0.3.1-py3-none-any.whl (7.0 kB)
Collecting pylev<2.0.0,>=1.3.0
  Using cached pylev-1.4.0-py2.py3-none-any.whl (6.1 kB)
Requirement already satisfied: async-timeout in c:\users\marsel\appdata\local\programs\python\python310\lib\site-packages (from aioredis<3.0.0,>=2.0.0->redis-om) (4.0.2)
Collecting colorama
  Using cached colorama-0.4.4-py2.py3-none-any.whl (16 kB)
Requirement already satisfied: deprecated>=1.2.3 in c:\users\marsel\appdata\local\programs\python\python310\lib\site-packages (from redis<5.0.0,>=3.5.3->redis-om) (1.2.13)
Requirement already satisfied: packaging>=20.4 in c:\users\marsel\appdata\local\programs\python\python310\lib\site-packages (from redis<5.0.0,>=3.5.3->redis-om) (21.3)
Requirement already satisfied: wrapt<2,>=1.10 in c:\users\marsel\appdata\local\programs\python\python310\lib\site-packages (from deprecated>=1.2.3->redis<5.0.0,>=3.5.3->redis-om) (1.14.0)
Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in c:\users\marsel\appdata\local\programs\python\python310\lib\site-packages (from packaging>=20.4->redis<5.0.0,>=3.5.3->redis-om) (3.0.7)
Using legacy 'setup.py install' for hiredis, since package 'wheel' is not installed.
Using legacy 'setup.py install' for pptree, since package 'wheel' is not installed.
Installing collected packages: types-six, types-redis, pylev, pptree, typing-extensions, six, python-ulid, python-dotenv, hiredis, crashtest, colorama, pydantic, click, cleo, aioredis, redis-om
  Running setup.py install for pptree ... done
  Running setup.py install for hiredis ... error
  error: subprocess-exited-with-error

  ร— Running setup.py install for hiredis did not run successfully.
  โ”‚ exit code: 1
  โ•ฐโ”€> [17 lines of output]
      C:\Users\Marsel\AppData\Local\Temp\pip-install-m8i9djzv\hiredis_6638e88d8f894ca2b3c269c6cc0a04ca\setup.py:7: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses
        import sys, imp, os, glob, io
      C:\Users\Marsel\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\dist.py:717: UserWarning: Usage of dash-separated 'description-file' will not be supported in future versions. Please use the underscore name 'description_file' instead
        warnings.warn(
      running install
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-3.10
      creating build\lib.win-amd64-3.10\hiredis
      copying hiredis\version.py -> build\lib.win-amd64-3.10\hiredis
      copying hiredis\__init__.py -> build\lib.win-amd64-3.10\hiredis
      copying hiredis\hiredis.pyi -> build\lib.win-amd64-3.10\hiredis
      copying hiredis\py.typed -> build\lib.win-amd64-3.10\hiredis
      running build_ext
      building 'hiredis.hiredis' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

ร— Encountered error while trying to install package.
โ•ฐโ”€> hiredis

note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.

When using `StrictInt`, integer values can't be retrieved with `get`?

I've created a basic model and set an int field to be StrictInt... this saves to Redis fine, but fails on retrieval... I imagine because this is really stored as a string in Redis.

Example code:

from redis_om import HashModel
from pydantic import StrictInt, ValidationError

class Adoptable(HashModel):
    name: str
    species: str
    age: StrictInt
    weight: float
    description: str

try:
    fido = Adoptable(
        name = "Fido",
        species = "dog",
        age = 3,
        weight = 37.2,
        description = "Fido is a fantastic dog in need of a new home"
    )

    print(fido.key())
    print("Saving Fido...")
    fido.save()

    print("Retrieving Fido...")
    an_adoptable = Adoptable.get(fido.pk)

    print(an_adoptable)

except ValidationError as e:
    print(e)

Running this yields:

$ python demo.py
:__main__.Adoptable:01FP6B9YCW6CZHNN1EY336WZ89
Saving Fido...
Retrieving Fido...
1 validation error for Adoptable
age
  value is not a valid integer (type=type_error.integer)

Python version:

$ python --version
Python 3.9.5

redis-om-python version:

redis-om==0.0.15

I was using this as a guide: https://github.com/redis/redis-om-python/blob/main/docs/getting_started.md#strict-validation

Fix test warnings

Fix the warnings that the tests emit regarding use of:

$ make test
...
DeprecationWarning: '@pytest.fixture' is applied to <fixture members, file=/Users/redacted/source/github/redis-om-python/tests_sync/test_oss_redis_features.py, line=45> in 'legacy' mode, please replace it with '@pytest_asyncio.fixture' as a preparation for switching to 'strict' mode (or use 'auto' mode to seamlessly handle all these fixtures as asyncio-driven).

This is in several files.

Deleting a record shouldn't require reading it first

It appears that in order to delete an instance of a model, it has to first be read from Redis:

def delete_person(id):
    person = Person.get(id)
    person.delete()
    return f"delete_person {id}"

The following would make more sense and avoids the reading step just to delete something:

def delete_person(id):
    Person.delete(id)
    return f"delete_person {id}"

The latter fails at the moment like so:

  File "/Users/simonprickett/source/github/redis-om-python-flask-skeleton-app/venv/lib/python3.9/site-packages/redis_om/model/model.py", line 1118, in delete
    return self.db().delete(self.key())
AttributeError: 'str' object has no attribute 'db'

change model in Redis Key prefix

When I save model in Redis
key will be
b':main.Customer:01FTA54AH0EP73X74HHM6HD3V8',
b':fastapi-1.Customer:01FTA3DY5VY6ATBHVWV9AS2DJ7',

How can I customize Key prefix?
make it look better and organize

  • from source :
db.hset(self.key(), mapping=document)

 def key(self):
        """Return the Redis key for this model."""
        pk = getattr(self, self._meta.primary_key.field.name)
        return self.make_primary_key(pk)

Wildcard searching in redis-om-python ?

Hi,

Can we perform (like in rediSearch) wildcard (asterisk) searching in redis-om in python ?

For this video - i tried for example:

Adoptable.find(Adoptable.name == 'A*').all()
but it does not do the job

Implement a configurable key namespace separator

Right not : is used for the key namespace separator. While this is the right answer most of the time, there are several places in the code marked with a TODO to make this configurable, which is a good idea but fairly low priority.

Index isn't created correctly when using full text search field?

I don't think the index is getting created correctly when using a full text search field... here a field description_fts is created in the index, but it doesn't say to use the field description as the field to search in... so I am unable to do any full text queries on description:

Model:

from typing import Text
from redis_om import (Field, HashModel)

class Adoptable(HashModel):
    name: str = Field(index=True)
    species: str = Field(index=True)
    age: int = Field(index=True)
    weight: float = Field(index=True)
    sex: str = Field(index=True)
    fee: float = Field(index=True)
    children: str = Field(index=True)
    other_animals: str = Field(index=True)
    description: str = Field(index=True, full_text_search=True)

FT.CREATE Redis command generated when I run migrator as seen by Redis MONITOR command:

"ft.create" ":adoptable.Adoptable:index" "ON" "HASH" "PREFIX" "1" ":adoptable.Adoptable:" "SCHEMA" "pk" "TAG" "SEPARATOR" "|" "name" "TAG" "SEPARATOR" "|" "species" "TAG" "SEPARATOR" "|" "age" "NUMERIC" "weight" "NUMERIC" "sex" "TAG" "SEPARATOR" "|" "fee" "NUMERIC" "children" "TAG" "SEPARATOR" "|" "other_animals" "TAG" "SEPARATOR" "|" "description" "TAG" "SEPARATOR" "|" "description_fts" "TEXT"

Hashes created using .save() don't have a description_fts field so this doesn't appear to work. Probably needs something like this in the index create command:

"description" "AS" "description_fts" "TEXT" 

I think the issue is here

f"{name}_fts TEXT"

which should likely say:

f"{name} AS {name}_fts TEXT "

EmbeddedJsonModel not working within a JsonModel

class Address(EmbeddedJsonModel):
    street: str

class Contact(JsonModel):
    name: str
    address: Address


data = {
    "name": "First",
    "address": {"street": "Main Rd"}
}

try:
    c = Contact(**data)
except Exception as e:
    print(e)

Always gets an error of Nonetype:

1 validation error for Contact
address
  'NoneType' object is not subscriptable (type=type_error)

If I change Address(EmbeddedJsonModel) -> Address(HashModel), it will work and embed it but the downside is that it creates a pk in each nested section.

What am I doing wrong?

Thanks

Fix 2 broken tests.

A couple of the tests are broken, diagnose the issues and fix them.

scheduling tests via LoadScheduling

tests/test_hash_model.py::test_full_text_search_queries
tests/test_hash_model.py::test_exact_match_queries
tests/test_hash_model.py::test_recursive_query_resolution
tests/test_hash_model.py::test_tag_queries_punctuation
tests/test_hash_model.py::test_tag_queries_negation
tests/test_hash_model.py::test_tag_queries_boolean_logic
tests/test_hash_model.py::test_numeric_queries
tests/test_hash_model.py::test_validates_required_fields
tests/test_hash_model.py::test_sorting
tests/test_hash_model.py::test_validates_field
tests/test_hash_model.py::test_validation_passes
tests/test_hash_model.py::test_raises_error_with_dataclasses
tests/test_hash_model.py::test_raises_error_with_sets
tests/test_hash_model.py::test_raises_error_with_dicts
tests/test_hash_model.py::test_saves_model_and_creates_pk
tests/test_hash_model.py::test_raises_error_with_embedded_models
[gw10] [  0%] PASSED tests/test_hash_model.py::test_validation_passes
[gw8] [  1%] PASSED tests/test_hash_model.py::test_validates_required_fields
[gw9] [  2%] PASSED tests/test_hash_model.py::test_validates_field
tests/test_json_model.py::test_saves_model_and_creates_pk
[gw14] [  3%] PASSED tests/test_hash_model.py::test_raises_error_with_dicts
[gw15] [  4%] PASSED tests/test_hash_model.py::test_raises_error_with_sets
tests/test_json_model.py::test_validates_field
[gw12] [  4%] PASSED tests/test_hash_model.py::test_raises_error_with_embedded_models
[gw13] [  5%] PASSED tests/test_hash_model.py::test_raises_error_with_dataclasses
tests/test_json_model.py::test_validation_passes
tests/test_json_model.py::test_access_result_by_index_cached
tests/test_json_model.py::test_saves_many_explicit_transaction
tests/test_json_model.py::test_paginate_query
[gw11] [  6%] PASSED tests/test_hash_model.py::test_saves_model_and_creates_pk
tests/test_json_model.py::test_updates_a_model
tests/test_json_model.py::test_saves_many_implicit_pipeline
[gw3] [  7%] PASSED tests/test_hash_model.py::test_tag_queries_boolean_logic
[gw2] [  8%] PASSED tests/test_hash_model.py::test_recursive_query_resolution
[gw1] [  9%] PASSED tests/test_hash_model.py::test_full_text_search_queries
tests/test_hash_model.py::test_paginate_query
tests/test_hash_model.py::test_saves_many
tests/test_hash_model.py::test_updates_a_model
[gw4] [  9%] PASSED tests/test_hash_model.py::test_tag_queries_punctuation
[gw7] [ 10%] PASSED tests/test_hash_model.py::test_sorting
tests/test_hash_model.py::test_access_result_by_index_cached
tests/test_json_model.py::test_validates_required_fields
[gw5] [ 11%] PASSED tests/test_hash_model.py::test_tag_queries_negation
[gw0] [ 12%] PASSED tests/test_hash_model.py::test_exact_match_queries
tests/test_hash_model.py::test_access_result_by_index_not_cached
tests/test_hash_model.py::test_raises_error_with_lists
[gw6] [ 13%] PASSED tests/test_hash_model.py::test_numeric_queries
tests/test_hash_model.py::test_schema
[gw8] [ 13%] PASSED tests/test_json_model.py::test_validates_field
[gw9] [ 14%] PASSED tests/test_json_model.py::test_validation_passes
tests/test_json_model.py::test_in_query
tests/test_json_model.py::test_update_query
[gw1] [ 15%] PASSED tests/test_hash_model.py::test_saves_many
[gw11] [ 16%] PASSED tests/test_json_model.py::test_saves_many_implicit_pipeline
tests/test_json_model.py::test_tag_queries_negation
[gw10] [ 17%] PASSED tests/test_json_model.py::test_saves_model_and_creates_pk
[gw0] [ 18%] PASSED tests/test_hash_model.py::test_raises_error_with_lists
[gw7] [ 18%] PASSED tests/test_json_model.py::test_validates_required_fields
[gw3] [ 19%] PASSED tests/test_hash_model.py::test_paginate_query
tests/test_json_model.py::test_tag_queries_boolean_logic
[gw4] [ 20%] PASSED tests/test_hash_model.py::test_access_result_by_index_cached
[gw2] [ 21%] PASSED tests/test_hash_model.py::test_updates_a_model
tests/test_json_model.py::test_access_result_by_index_not_cached
[gw15] [ 22%] PASSED tests/test_json_model.py::test_access_result_by_index_cached
tests/test_json_model.py::test_not_found
[gw6] [ 22%] PASSED tests/test_hash_model.py::test_schema
tests/test_json_model.py::test_allows_dataclasses
tests/test_json_model.py::test_sorting
tests/test_json_model.py::test_numeric_queries
tests/test_json_model.py::test_tag_queries_punctuation
tests/test_json_model.py::test_exact_match_queries
tests/test_json_model.py::test_allows_and_serializes_dicts
[gw14] [ 23%] PASSED tests/test_json_model.py::test_paginate_query
[gw12] [ 24%] PASSED tests/test_json_model.py::test_saves_many_explicit_transaction
[gw13] [ 25%] PASSED tests/test_json_model.py::test_updates_a_model
[gw5] [ 26%] PASSED tests/test_hash_model.py::test_access_result_by_index_not_cached
tests/test_json_model.py::test_recursive_query_expression_resolution
tests/test_json_model.py::test_recursive_query_field_resolution
tests/test_json_model.py::test_full_text_search
tests/test_json_model.py::test_list_field_limitations
[gw7] [ 27%] PASSED tests/test_json_model.py::test_not_found
tests/test_oss_redis_features.py::test_validates_required_fields
[gw11] [ 27%] PASSED tests/test_json_model.py::test_tag_queries_boolean_logic
tests/test_oss_redis_features.py::test_all_keys
[gw8] [ 28%] PASSED tests/test_json_model.py::test_in_query
[gw0] [ 29%] PASSED tests/test_json_model.py::test_allows_dataclasses
[gw9] [ 30%] PASSED tests/test_json_model.py::test_update_query
tests/test_json_model.py::test_allows_and_serializes_sets
tests/test_oss_redis_features.py::test_validates_field
tests/test_json_model.py::test_allows_and_serializes_lists
[gw14] [ 31%] PASSED tests/test_json_model.py::test_recursive_query_expression_resolution
[gw6] [ 31%] PASSED tests/test_json_model.py::test_allows_and_serializes_dicts
[gw1] [ 32%] PASSED tests/test_json_model.py::test_tag_queries_negation
tests_sync/test_hash_model.py::test_exact_match_queries
[gw3] [ 33%] PASSED tests/test_json_model.py::test_tag_queries_punctuation
tests/test_oss_redis_features.py::test_updates_a_model
tests/test_json_model.py::test_schema
tests/test_oss_redis_features.py::test_raises_error_with_embedded_models
[gw10] [ 34%] PASSED tests/test_json_model.py::test_access_result_by_index_not_cached
tests/test_oss_redis_features.py::test_not_found
[gw7] [ 35%] PASSED tests/test_oss_redis_features.py::test_validates_required_fields
tests_sync/test_hash_model.py::test_tag_queries_boolean_logic
[gw2] [ 36%] PASSED tests/test_json_model.py::test_numeric_queries
tests/test_oss_redis_features.py::test_saves_model_and_creates_pk
[gw4] [ 36%] PASSED tests/test_json_model.py::test_sorting
tests/test_oss_redis_features.py::test_validation_passes
[gw9] [ 37%] PASSED tests/test_json_model.py::test_allows_and_serializes_lists
[gw8] [ 38%] PASSED tests/test_json_model.py::test_allows_and_serializes_sets
[gw15] [ 39%] PASSED tests/test_json_model.py::test_exact_match_queries
tests_sync/test_hash_model.py::test_sorting
tests_sync/test_hash_model.py::test_numeric_queries
[gw13] [ 40%] PASSED tests/test_json_model.py::test_full_text_search
[gw12] [ 40%] PASSED tests/test_json_model.py::test_recursive_query_field_resolution
tests/test_oss_redis_features.py::test_saves_many
[gw0] [ 41%] PASSED tests/test_oss_redis_features.py::test_validates_field
tests_sync/test_hash_model.py::test_full_text_search_queries
tests/test_pydantic_integrations.py::test_email_str
tests_sync/test_hash_model.py::test_tag_queries_negation
[gw1] [ 42%] PASSED tests/test_json_model.py::test_schema
tests_sync/test_hash_model.py::test_validation_passes
[gw14] [ 43%] PASSED tests_sync/test_hash_model.py::test_exact_match_queries
[gw3] [ 44%] PASSED tests/test_oss_redis_features.py::test_raises_error_with_embedded_models
[gw10] [ 45%] PASSED tests/test_oss_redis_features.py::test_not_found
tests_sync/test_hash_model.py::test_validates_required_fields
[gw5] [ 45%] PASSED tests/test_json_model.py::test_list_field_limitations
tests_sync/test_hash_model.py::test_saves_model_and_creates_pk
tests_sync/test_hash_model.py::test_raises_error_with_embedded_models
[gw7] [ 46%] PASSED tests_sync/test_hash_model.py::test_tag_queries_boolean_logic
tests_sync/test_hash_model.py::test_recursive_query_resolution
tests_sync/test_hash_model.py::test_raises_error_with_dataclasses
[gw11] [ 47%] PASSED tests/test_oss_redis_features.py::test_all_keys
[gw2] [ 48%] PASSED tests/test_oss_redis_features.py::test_saves_model_and_creates_pk
tests_sync/test_hash_model.py::test_raises_error_with_dicts
tests_sync/test_hash_model.py::test_tag_queries_punctuation
[gw4] [ 49%] PASSED tests/test_oss_redis_features.py::test_validation_passes
tests_sync/test_hash_model.py::test_raises_error_with_sets
[gw6] [ 50%] PASSED tests/test_oss_redis_features.py::test_updates_a_model
tests_sync/test_hash_model.py::test_validates_field
[gw1] [ 50%] PASSED tests_sync/test_hash_model.py::test_validation_passes
[gw9] [ 51%] PASSED tests_sync/test_hash_model.py::test_sorting
tests_sync/test_hash_model.py::test_schema
tests_sync/test_hash_model.py::test_raises_error_with_lists
[gw14] [ 52%] PASSED tests_sync/test_hash_model.py::test_validates_required_fields
tests_sync/test_json_model.py::test_validates_required_fields
[gw15] [ 53%] PASSED tests/test_oss_redis_features.py::test_saves_many
[gw7] [ 54%] PASSED tests_sync/test_hash_model.py::test_raises_error_with_dataclasses
[gw10] [ 54%] PASSED tests_sync/test_hash_model.py::test_raises_error_with_embedded_models
[gw3] [ 55%] PASSED tests_sync/test_hash_model.py::test_saves_model_and_creates_pk
tests_sync/test_hash_model.py::test_updates_a_model
[gw0] [ 56%] PASSED tests_sync/test_hash_model.py::test_tag_queries_negation
[gw2] [ 57%] PASSED tests_sync/test_hash_model.py::test_raises_error_with_dicts
tests_sync/test_json_model.py::test_saves_many_implicit_pipeline
tests_sync/test_json_model.py::test_validation_passes
tests_sync/test_json_model.py::test_validates_field
[gw4] [ 58%] PASSED tests_sync/test_hash_model.py::test_raises_error_with_sets
tests_sync/test_hash_model.py::test_access_result_by_index_not_cached
tests_sync/test_json_model.py::test_saves_many_explicit_transaction
tests_sync/test_json_model.py::test_paginate_query
[gw5] [ 59%] PASSED tests_sync/test_hash_model.py::test_recursive_query_resolution
tests_sync/test_json_model.py::test_saves_model_and_creates_pk
[gw6] [ 59%] PASSED tests_sync/test_hash_model.py::test_validates_field
[gw1] [ 60%] PASSED tests_sync/test_hash_model.py::test_schema
tests_sync/test_json_model.py::test_access_result_by_index_cached
[gw11] [ 61%] PASSED tests_sync/test_hash_model.py::test_tag_queries_punctuation
[gw9] [ 62%] PASSED tests_sync/test_hash_model.py::test_raises_error_with_lists
tests_sync/test_json_model.py::test_access_result_by_index_not_cached
tests_sync/test_json_model.py::test_updates_a_model
tests_sync/test_json_model.py::test_in_query
[gw14] [ 63%] PASSED tests_sync/test_json_model.py::test_validates_required_fields
tests_sync/test_json_model.py::test_update_query
[gw3] [ 63%] PASSED tests_sync/test_json_model.py::test_validates_field
tests_sync/test_json_model.py::test_full_text_search
[gw13] [ 64%] FAILED tests_sync/test_hash_model.py::test_full_text_search_queries
[gw7] [ 65%] PASSED tests_sync/test_json_model.py::test_saves_many_implicit_pipeline
[gw8] [ 66%] FAILED tests_sync/test_hash_model.py::test_numeric_queries
tests_sync/test_hash_model.py::test_paginate_query
tests_sync/test_json_model.py::test_recursive_query_expression_resolution
[gw15] [ 67%] PASSED tests_sync/test_hash_model.py::test_updates_a_model
tests_sync/test_hash_model.py::test_saves_many
[gw10] [ 68%] PASSED tests_sync/test_json_model.py::test_validation_passes
tests_sync/test_json_model.py::test_exact_match_queries
tests_sync/test_json_model.py::test_recursive_query_field_resolution
[gw2] [ 68%] PASSED tests_sync/test_json_model.py::test_saves_many_explicit_transaction
tests_sync/test_json_model.py::test_tag_queries_punctuation
[gw0] [ 69%] PASSED tests_sync/test_hash_model.py::test_access_result_by_index_not_cached
tests_sync/test_json_model.py::test_tag_queries_boolean_logic
[gw4] [ 70%] PASSED tests_sync/test_json_model.py::test_paginate_query
[gw5] [ 71%] PASSED tests_sync/test_json_model.py::test_saves_model_and_creates_pk
tests_sync/test_json_model.py::test_tag_queries_negation
tests_sync/test_json_model.py::test_numeric_queries
[gw9] [ 72%] PASSED tests_sync/test_json_model.py::test_in_query
[gw6] [ 72%] PASSED tests_sync/test_json_model.py::test_access_result_by_index_cached
tests_sync/test_json_model.py::test_allows_dataclasses
tests_sync/test_json_model.py::test_sorting
[gw8] [ 73%] PASSED tests_sync/test_hash_model.py::test_saves_many
[gw14] [ 74%] PASSED tests_sync/test_json_model.py::test_update_query
tests_sync/test_oss_redis_features.py::test_all_keys
tests_sync/test_json_model.py::test_allows_and_serializes_dicts
[gw11] [ 75%] PASSED tests_sync/test_json_model.py::test_updates_a_model
tests_sync/test_json_model.py::test_list_field_limitations
[gw1] [ 76%] PASSED tests_sync/test_json_model.py::test_access_result_by_index_not_cached
[gw13] [ 77%] PASSED tests_sync/test_hash_model.py::test_paginate_query
tests_sync/test_json_model.py::test_not_found
[gw7] [ 77%] PASSED tests_sync/test_json_model.py::test_recursive_query_expression_resolution
tests_sync/test_json_model.py::test_allows_and_serializes_lists
[gw3] [ 78%] PASSED tests_sync/test_json_model.py::test_full_text_search
tests_sync/test_json_model.py::test_schema
tests_sync/test_json_model.py::test_allows_and_serializes_sets
[gw9] [ 79%] PASSED tests_sync/test_json_model.py::test_allows_dataclasses
[gw0] [ 80%] PASSED tests_sync/test_json_model.py::test_tag_queries_boolean_logic
tests_sync/test_oss_redis_features.py::test_saves_many
[gw2] [ 81%] PASSED tests_sync/test_json_model.py::test_tag_queries_punctuation
tests_sync/test_oss_redis_features.py::test_validation_passes
tests_sync/test_oss_redis_features.py::test_validates_field
[gw10] [ 81%] PASSED tests_sync/test_json_model.py::test_recursive_query_field_resolution
tests_sync/test_oss_redis_features.py::test_validates_required_fields
[gw6] [ 82%] PASSED tests_sync/test_json_model.py::test_sorting
[gw15] [ 83%] PASSED tests_sync/test_json_model.py::test_exact_match_queries
tests_sync/test_oss_redis_features.py::test_not_found
tests_sync/test_oss_redis_features.py::test_updates_a_model
[gw4] [ 84%] PASSED tests_sync/test_json_model.py::test_tag_queries_negation
tests_sync/test_oss_redis_features.py::test_saves_model_and_creates_pk
[gw5] [ 85%] PASSED tests_sync/test_json_model.py::test_numeric_queries
[gw14] [ 86%] PASSED tests_sync/test_json_model.py::test_allows_and_serializes_dicts
tests_sync/test_oss_redis_features.py::test_raises_error_with_embedded_models
[gw1] [ 86%] PASSED tests_sync/test_json_model.py::test_not_found
[gw7] [ 87%] PASSED tests_sync/test_json_model.py::test_schema
[gw13] [ 88%] PASSED tests_sync/test_json_model.py::test_allows_and_serializes_lists
[gw3] [ 89%] PASSED tests_sync/test_json_model.py::test_allows_and_serializes_sets
[gw0] [ 90%] PASSED tests_sync/test_oss_redis_features.py::test_validation_passes
[gw2] [ 90%] PASSED tests_sync/test_oss_redis_features.py::test_validates_field
[gw10] [ 91%] PASSED tests_sync/test_oss_redis_features.py::test_validates_required_fields
[gw11] [ 92%] PASSED tests_sync/test_json_model.py::test_list_field_limitations
[gw15] [ 93%] PASSED tests_sync/test_oss_redis_features.py::test_not_found
[gw9] [ 94%] PASSED tests_sync/test_oss_redis_features.py::test_saves_many
[gw6] [ 95%] PASSED tests_sync/test_oss_redis_features.py::test_updates_a_model
[gw5] [ 95%] PASSED tests_sync/test_oss_redis_features.py::test_raises_error_with_embedded_models
[gw4] [ 96%] PASSED tests_sync/test_oss_redis_features.py::test_saves_model_and_creates_pk
[gw8] [ 97%] PASSED tests_sync/test_oss_redis_features.py::test_all_keys
tests_sync/test_pydantic_integrations.py::test_email_str
[gw12] [ 98%] PASSED tests/test_pydantic_integrations.py::test_email_str
tests_sync/test_hash_model.py::test_access_result_by_index_cached
[gw12] [ 99%] PASSED tests_sync/test_hash_model.py::test_access_result_by_index_cached
[gw8] [100%] PASSED tests_sync/test_pydantic_integrations.py::test_email_str

============================================ FAILURES ============================================
_________________________________ test_full_text_search_queries __________________________________
[gw13] darwin -- Python 3.9.5 /Users/simonprickett/Library/Caches/pypoetry/virtualenvs/redis-om-dXPLVk-w-py3.9/bin/python

members = (Member(pk='01FS5ATV1SMS7T8PG5MJM4PB7P', first_name='Andrew', last_name='Brookins', email='[email protected]', join_date=d...com', join_date=datetime.date(2022, 1, 11), age=100, bio='This is member 3 who is a funny and lively sort of person.'))
m = Models(BaseHashModel=<class 'tests_sync.test_hash_model.m.<locals>.BaseHashModel'>, Order=<class 'tests_sync.test_hash_model.m.<locals>.Order'>, Member=<class 'tests_sync.test_hash_model.m.<locals>.Member'>)

    @pytest.mark.asyncio
    def test_full_text_search_queries(members, m):
        member1, member2, member3 = members

        actual = (
            m.Member.find(m.Member.bio % "great").all()
        )

        assert actual == [member1]

        actual = (
            m.Member.find(~(m.Member.bio % "anxious")).all()
        )

>       assert actual == [member1, member3]
E       AssertionError: assert [Member(pk='01FS5ATV1SEMK9FDCVQ4075VPR', first_name='Andrew', last_name='Smith', email='[email protected]', join_date=datetime.date(2022, 1, 11), age=100, bio='This is member 3 who is a funny and lively sort of person.'),\n Member(pk='01FS5ATV1SMS7T8PG5MJM4PB7P', first_name='Andrew', last_name='Brookins', email='[email protected]', join_date=datetime.date(2022, 1, 11), age=38, bio='This is member 1 whose greatness makes him the life and soul of any party he goes to.')] == [Member(pk='01FS5ATV1SMS7T8PG5MJM4PB7P', first_name='Andrew', last_name='Brookins', email='[email protected]', join_date=datetime.date(2022, 1, 11), age=38, bio='This is member 1 whose greatness makes him the life and soul of any party he goes to.'),\n Member(pk='01FS5ATV1SEMK9FDCVQ4075VPR', first_name='Andrew', last_name='Smith', email='[email protected]', join_date=datetime.date(2022, 1, 11), age=100, bio='This is member 3 who is a funny and lively sort of person.')]
E         At index 0 diff: Member(pk='01FS5ATV1SEMK9FDCVQ4075VPR', first_name='Andrew', last_name='Smith', email='[email protected]', join_date=datetime.date(2022, 1, 11), age=100, bio='This is member 3 who is a funny and lively sort of person.') != Member(pk='01FS5ATV1SMS7T8PG5MJM4PB7P', first_name='Andrew', last_name='Brookins', email='[email protected]', join_date=datetime.date(2022, 1, 11), age=38, bio='This is member 1 whose greatness makes him the life and soul of any party he goes to.')
E         Full diff:
E           [
E         +  Member(pk='01FS5ATV1SEMK9FDCVQ4075VPR', first_name='Andrew', last_name='Smith', email='[email protected]', join_date=datetime.date(2022, 1, 11), age=100, bio='This is member 3 who is a funny and lively sort of person.'),
E            Member(pk='01FS5ATV1SMS7T8PG5MJM4PB7P', first_name='Andrew', last_name='Brookins', email='[email protected]', join_date=datetime.date(2022, 1, 11), age=38, bio='This is member 1 whose greatness makes him the life and soul of any party he goes to.'),
E         -  Member(pk='01FS5ATV1SEMK9FDCVQ4075VPR', first_name='Andrew', last_name='Smith', email='[email protected]', join_date=datetime.date(2022, 1, 11), age=100, bio='This is member 3 who is a funny and lively sort of person.'),
E           ]

tests_sync/test_hash_model.py:145: AssertionError
______________________________________ test_numeric_queries ______________________________________
[gw8] darwin -- Python 3.9.5 /Users/simonprickett/Library/Caches/pypoetry/virtualenvs/redis-om-dXPLVk-w-py3.9/bin/python

members = (Member(pk='01FS5ATV1DNY2P4WKGYVMZKCXF', first_name='Andrew', last_name='Brookins', email='[email protected]', join_date=d...com', join_date=datetime.date(2022, 1, 11), age=100, bio='This is member 3 who is a funny and lively sort of person.'))
m = Models(BaseHashModel=<class 'tests_sync.test_hash_model.m.<locals>.BaseHashModel'>, Order=<class 'tests_sync.test_hash_model.m.<locals>.Order'>, Member=<class 'tests_sync.test_hash_model.m.<locals>.Member'>)

    @pytest.mark.asyncio
    def test_numeric_queries(members, m):
        member1, member2, member3 = members

        actual = m.Member.find(m.Member.age == 34).all()
        assert actual == [member2]

        actual = m.Member.find(m.Member.age > 34).sort_by("age").all()
        assert actual == [member1, member3]

        actual = m.Member.find(m.Member.age < 35).all()
        assert actual == [member2]

        actual = m.Member.find(m.Member.age <= 34).all()
        assert actual == [member2]

        actual = m.Member.find(m.Member.age >= 100).all()
        assert actual == [member3]

        actual = m.Member.find(m.Member.age != 34).sort_by("age").all()
        assert actual == [member1, member3]

        actual = m.Member.find(~(m.Member.age == 100)).sort_by("age").all()
>       assert actual == [member2, member1]
E       AssertionError: assert [Member(pk='01FS5ATV1D5SWT66T89028YN2X', first_name='Kim', last_name='Brookins', email='[email protected]', join_date=datetime.date(2022, 1, 11), age=34, bio='This is member 2 who can be quite anxious until you get to know them.')] == [Member(pk='01FS5ATV1D5SWT66T89028YN2X', first_name='Kim', last_name='Brookins', email='[email protected]', join_date=datetime.date(2022, 1, 11), age=34, bio='This is member 2 who can be quite anxious until you get to know them.'),\n Member(pk='01FS5ATV1DNY2P4WKGYVMZKCXF', first_name='Andrew', last_name='Brookins', email='[email protected]', join_date=datetime.date(2022, 1, 11), age=38, bio='This is member 1 whose greatness makes him the life and soul of any party he goes to.')]
E         Right contains one more item: Member(pk='01FS5ATV1DNY2P4WKGYVMZKCXF', first_name='Andrew', last_name='Brookins', email='[email protected]', join_date=da...date(2022, 1, 11), age=38, bio='This is member 1 whose greatness makes him the life and soul of any party he goes to.')
E         Full diff:
E           [
E            Member(pk='01FS5ATV1D5SWT66T89028YN2X', first_name='Kim', last_name='Brookins', email='[email protected]', join_date=datetime.date(2022, 1, 11), age=34, bio='This is member 2 who can be quite anxious until you get to know them.'),
E         -  Member(pk='01FS5ATV1DNY2P4WKGYVMZKCXF', first_name='Andrew', last_name='Brookins', email='[email protected]', join_date=datetime.date(2022, 1, 11), age=38, bio='This is member 1 whose greatness makes him the life and soul of any party he goes to.'),
E           ]

tests_sync/test_hash_model.py:310: AssertionError

---------- coverage: platform darwin, python 3.9.5-final-0 -----------
Name                                     Stmts   Miss  Cover   Missing
----------------------------------------------------------------------
aredis_om/__init__.py                        4      0   100%
aredis_om/checks.py                         21     12    43%   9-10, 14-17, 21-26
aredis_om/connections.py                    12      3    75%   20-22
aredis_om/model/__init__.py                  2      0   100%
aredis_om/model/cli/__init__.py              0      0   100%
aredis_om/model/cli/migrate.py              13     13     0%   1-18
aredis_om/model/encoders.py                 72     35    51%   68, 70, 73-86, 94, 96, 98, 132-147, 150-155, 159-173
aredis_om/model/migrations/__init__.py       0      0   100%
aredis_om/model/migrations/migrator.py      84     14    83%   24-35, 49, 76-77, 82-83, 94, 105-107
aredis_om/model/model.py                   857    118    86%   97, 108, 125, 133, 142-149, 163, 182, 190, 196, 200, 204, 208-211, 215, 238, 242, 294, 302, 348, 388, 395, 413, 440, 468, 493, 496-502, 521, 523, 527, 555-565, 583-586, 597, 644, 658-663, 676, 690, 692, 694, 696, 754, 765, 795, 798-803, 819-829, 879, 902-903, 1047, 1110, 1118, 1122, 1126, 1129, 1145, 1147, 1178-1181, 1261, 1267, 1327-1335, 1349, 1380, 1389-1398, 1402, 1417-1425, 1436-1446, 1459, 1543-1544, 1571-1574, 1658, 1662-1666
aredis_om/model/query_resolver.py           23     23     0%   1-103
aredis_om/model/render_tree.py              33     31     6%   24-75
aredis_om/model/token_escaper.py            13      1    92%   16
aredis_om/unasync_util.py                   20      7    65%   14, 18, 28, 32-34, 41
----------------------------------------------------------------------
TOTAL                                     1154    257    78%

==================================== short test summary info =====================================
FAILED tests_sync/test_hash_model.py::test_full_text_search_queries - AssertionError: assert [M...
FAILED tests_sync/test_hash_model.py::test_numeric_queries - AssertionError: assert [Member(pk=...
================================= 2 failed, 120 passed in 3.75s ==================================
make: *** [Makefile:66: test] Error 1

JsonModel: find not working with Optional and no default

Hello,

In JsonModel, find not working with class that has Optional and no default value, whereas HashModel is working

Check out below code:

class CustomerHash1(HashModel):
    name: str = Field(index=True)
    bio: Optional[str]


class CustomerHash2(HashModel):
    name: str = Field(index=True)
    bio: Optional[str] = Field(title="bio")


class CustomerHash3(HashModel):
    name: str = Field(index=True)
    bio: Optional[str] = Field(title="bio", default="")


class CustomerJson1(JsonModel):
    name: str = Field(index=True)
    bio: Optional[str]

# Not Working
class CustomerJson2(JsonModel):
    name: str = Field(index=True)
    bio: Optional[str] = Field(title="bio")


class CustomerJson3(JsonModel):
    name: str = Field(index=True)
    bio: Optional[str] = Field(title="bio", default="")

Migrator().run()

# Hash
CustomerHash1(name="Brookins").save()
print(
    "HashModel with Optional and field: ",
    CustomerHash1.find(CustomerHash1.name == "Brookins").all(),
)
CustomerHash2(name="Brookins").save()
print(
    "HashModel with Optional and no default: ",
    CustomerHash2.find(CustomerHash2.name == "Brookins").all(),
)
CustomerHash3(name="Brookins").save()
print(
    "HashModel with Optional and default: ",
    CustomerHash3.find(CustomerHash3.name == "Brookins").all(),
)


# Json
CustomerJson1(name="Brookins").save()
print(
    "JsonModel with Optional and field: ",
    CustomerJson1.find(CustomerJson1.name == "Brookins").all(),
)
# Not Working
CustomerJson2(name="Brookins").save()
print(
    "JsonModel with Optional and no default: ",
    CustomerJson2.find(CustomerJson2.name == "Brookins").all(),
)
CustomerJson3(name="Brookins").save()
print(
    "JsonModel with Optional and default: ",
    CustomerJson3.find(CustomerJson3.name == "Brookins").all(),
)

Results:

HashModel with Optional and field:  [CustomerHash1(pk='01FR9YSQ61BKYERVVCZRYED6NG', name='Brookins', bio='')]
HashModel with Optional and no default:  [CustomerHash2(pk='01FR9YSQ64EXHRSA82HS9G9ZW6', name='Brookins', bio='')]
HashModel with Optional and default:  [CustomerHash3(pk='01FR9YSQ66FCNFB1GC55JR4NPZ', name='Brookins', bio='')]
JsonModel with Optional and field:  [CustomerJson1(pk='01FR9YSQ698MJTYY06KCTB3CQC', name='Brookins', bio=None)]
JsonModel with Optional and no default:  []
JsonModel with Optional and default:  [CustomerJson3(pk='01FR9YSQ6DXZZBY1BVMZWN59GC', name='Brookins', bio='')]

Does the redismod container need to use append only?

The Redis server in the redismod container used for runnign tests has an append only file configured. Is this needed?

If not, then this:

services:
  redis:
    image: "redislabs/redismod:edge"
    entrypoint: ["redis-server", "--appendonly", "yes", "--loadmodule", "/usr/lib/redis/modules/rejson.so", "--loadmodule", "/usr/lib/redis/modules/redisearch.so"]
    restart: always
    ports:
      - "6380:6379"
    volumes:
      - ./data:/data

could be updated / simplified to:

services:
  redis:
    image: "redislabs/redismod:edge"
    entrypoint: ["redis-server", "--loadmodule", "/usr/lib/redis/modules/rejson.so", "--loadmodule", "/usr/lib/redis/modules/redisearch.so"]
    restart: always
    ports:
      - "6380:6379"

Document querying

Add a Markdown document to docs/ with more in-depth querying examples.

JsonModel: find not working with timedelta

Hello,

In JsonModel, find not working with timedelta, whereas HashModel is working

Check out below code:

class Customer(JsonModel):
    name: str = Field(title="Name", index=True)


class RestaurantVisit1(JsonModel):
    customer_pk: str = Field(index=True)
    registered_at: datetime.datetime = Field(title="Registered At")

# Not Working
class RestaurantVisit2(JsonModel):
    customer_pk: str = Field(index=True)
    registered_at: datetime.datetime = Field(title="Registered At")
    waiting_duration: datetime.timedelta = Field(title="Waiting Duration")


class RestaurantVisit3(HashModel):
    customer_pk: str = Field(index=True)
    registered_at: datetime.datetime = Field(title="Registered At")
    waiting_duration: datetime.timedelta = Field(title="Waiting Duration")

Migrator().run()

c = Customer(name="Brookins").save()
v1 = RestaurantVisit1(
    customer_pk=c.pk,
    registered_at=datetime.datetime.now(),
).save()
v2 = RestaurantVisit2(
    customer_pk=c.pk,
    registered_at=datetime.datetime.now(),
    waiting_duration=datetime.timedelta(minutes=15),
).save()
v3 = RestaurantVisit3(
    customer_pk=c.pk,
    registered_at=datetime.datetime.now(),
    waiting_duration=datetime.timedelta(minutes=15),
).save()

print("Customer Get: ", Customer.get(pk=c.pk))
print("Customer Find: ", Customer.find(Customer.name == "Brookins").all())
print("RestaurantVisit1 Get: ", RestaurantVisit1.get(pk=v1.pk))
print(
    "RestaurantVisit1 Find: ",
    RestaurantVisit1.find(RestaurantVisit1.customer_pk == c.pk).all(),
)
print("RestaurantVisit2 with datetime.timedelta Get: ", RestaurantVisit2.get(pk=v2.pk))
# Not Working
print(
    "RestaurantVisit2 with datetime.timedelta Find: ",
    RestaurantVisit2.find(RestaurantVisit2.customer_pk == c.pk).all(),
)
print(
    "RestaurantVisit3 with datetime.timedelta HashModel Get: ",
    RestaurantVisit3.get(pk=v3.pk),
)
print(
    "RestaurantVisit3 with datetime.timedelta HashModel Find: ",
    RestaurantVisit3.find(RestaurantVisit3.customer_pk == c.pk).all(),
)

Results:

Customer Get:  pk='01FRAFY4KDH6Q0TRQ6CX7JJ6Z2' name='Brookins'
Customer Find:  [Customer(pk='01FRAFY4KDH6Q0TRQ6CX7JJ6Z2', name='Brookins')]
RestaurantVisit1 Get:  pk='01FRAFY4KGGAYFG7JZ468417FG' customer_pk='01FRAFY4KDH6Q0TRQ6CX7JJ6Z2' registered_at=datetime.datetime(2022, 1, 1, 12, 36, 7, 792310)
RestaurantVisit1 Find:  [RestaurantVisit1(pk='01FRAFY4KGGAYFG7JZ468417FG', customer_pk='01FRAFY4KDH6Q0TRQ6CX7JJ6Z2', registered_at=datetime.datetime(2022, 1, 1, 12, 36, 7, 792310))]
RestaurantVisit2 with datetime.timedelta Get:  pk='01FRAFY4KKYTJE78EBQNBHP9KE' customer_pk='01FRAFY4KDH6Q0TRQ6CX7JJ6Z2' registered_at=datetime.datetime(2022, 1, 1, 12, 36, 7, 795804) waiting_duration=datetime.timedelta(seconds=900)
RestaurantVisit2 with datetime.timedelta Find:  []
RestaurantVisit3 with datetime.timedelta HashModel Get:  pk='01FRAFY4KN7Y5YZ3TRGKEQNS8R' customer_pk='01FRAFY4KDH6Q0TRQ6CX7JJ6Z2' registered_at=datetime.datetime(2022, 1, 1, 12, 36, 7, 797948) waiting_duration=datetime.timedelta(seconds=900)
RestaurantVisit3 with datetime.timedelta HashModel Find:  [RestaurantVisit3(pk='01FRAFY4KN7Y5YZ3TRGKEQNS8R', customer_pk='01FRAFY4KDH6Q0TRQ6CX7JJ6Z2', registered_at=datetime.datetime(2022, 1, 1, 12, 36, 7, 797948), waiting_duration=datetime.timedelta(seconds=900))]

Address failing test cases?

I see 19 test cases failing on main:

$ make test
...
================================== short test summary info ==================================
FAILED tests/test_json_model.py::test_exact_match_queries - AssertionError: assert [] == [...
FAILED tests/test_json_model.py::test_update_query - assert 0 == 3
FAILED tests/test_json_model.py::test_tag_queries_negation - AssertionError: assert [Membe...
FAILED tests/test_json_model.py::test_in_query - AssertionError: assert [] == [Member(pk='...
FAILED tests/test_json_model.py::test_recursive_query_field_resolution - AssertionError: a...
FAILED tests/test_json_model.py::test_recursive_query_expression_resolution - AssertionErr...
FAILED tests/test_json_model.py::test_tag_queries_boolean_logic - AssertionError: assert [...
FAILED tests/test_json_model.py::test_list_field_limitations - AssertionError: assert [] =...
FAILED tests/test_json_model.py::test_tag_queries_punctuation - aredis_om.model.model.NotF...
FAILED tests_sync/test_json_model.py::test_recursive_query_expression_resolution - Asserti...
FAILED tests_sync/test_json_model.py::test_exact_match_queries - AssertionError: assert []...
FAILED tests_sync/test_json_model.py::test_update_query - assert 0 == 3
FAILED tests_sync/test_json_model.py::test_in_query - AssertionError: assert [] == [Member...
FAILED tests_sync/test_json_model.py::test_recursive_query_field_resolution - AssertionErr...
FAILED tests_sync/test_json_model.py::test_tag_queries_boolean_logic - AssertionError: ass...
FAILED tests_sync/test_json_model.py::test_tag_queries_punctuation - redis_om.model.model....
FAILED tests_sync/test_json_model.py::test_tag_queries_negation - AssertionError: assert [...
FAILED tests_sync/test_json_model.py::test_list_field_limitations - AssertionError: assert...
FAILED tests_sync/test_oss_redis_features.py::test_all_keys - assert 2 == 3
============================== 19 failed, 101 passed in 4.07s ===============================

Unable to connect

Cannot connect redis_om with django, was able to successfully connect redis-py with django using:
redis.StrictRedis(host='127.0.0.1', port=6379, db=0)
but when tried to connect the redis-om-model with django and fetched the existing data using:

`redis_om_conc = get_redis_connection(
url="redis://127.0.0.1:6379/0",
decode_responses=True
)

class GameList(HashModel):
class Meta:
database = redis_om_conc

game_id: int
game_name: str
game_code: str
display_platform: int
vendor: str
vendor_code: str
vendor_id: int
languages: str
external_game_id: str

GameList.get("01FVF51D2K8WWTR2BTME97SWZ1")`

it throws an error as:

`NotFoundError Traceback (most recent call last)
Input In [12], in
----> 1 GameList.get("01FVF51D2K8WWTR2BTME97SWZ1")

File ~/Projects/Feeder/cron-env/lib/python3.8/site-packages/redis_om/model/model.py:1324, in HashModel.get(cls, pk)
1322 document = cls.db().hgetall(cls.make_primary_key(pk))
1323 if not document:
-> 1324 raise NotFoundError
1325 try:
1326 result = cls.parse_obj(document)

NotFoundError:`

TypeError: 'NoneType' object is not subscriptable on find query

Hi Dears i got error on find query with below information:

class Customer(HashModel):
first_name: str
last_name: str = Field(index=True)

class Meta:
    database = redis

Customer.find(Customer.last_name == "Brookins").all()

Error is:
TypeError: 'NoneType' object is not subscriptable

no such index

Set a db number other than 0, I got an error.

import datetime
from typing import Optional

from redis_om import Field, JsonModel, Migrator, get_redis_connection


class Customer(JsonModel):
    first_name: str
    last_name: str = Field(index=True)
    email: str
    join_date: datetime.date
    age: int = Field(index=True)
    bio: Optional[str]

    class Meta:
        database = get_redis_connection(host="redis", port=6379, db=1)


andrew = Customer(
    first_name="Andrew",
    last_name="Brookins",
    email="[email protected]",
    join_date=datetime.date.today(),
    age=38,
)
andrew.save()
Migrator().run()

# Find all customers with the last name "Brookins"
result = Customer.find(Customer.last_name == "Brookins").all()

error

Traceback (most recent call last):
  File "/app/aaa.py", line 30, in <module>
    Customer.find(Customer.last_name == "Brookins").all()
  File "/opt/pysetup/.venv/lib/python3.10/site-packages/redis_om/model/model.py", line 761, in all
    return self.execute()
  File "/opt/pysetup/.venv/lib/python3.10/site-packages/redis_om/model/model.py", line 725, in execute
    raw_result = self.model.db().execute_command(*args)
  File "/opt/pysetup/.venv/lib/python3.10/site-packages/redis/client.py", line 1173, in execute_command
    return conn.retry.call_with_retry(
  File "/opt/pysetup/.venv/lib/python3.10/site-packages/redis/retry.py", line 41, in call_with_retry
    return do()
  File "/opt/pysetup/.venv/lib/python3.10/site-packages/redis/client.py", line 1174, in <lambda>
    lambda: self._send_command_parse_response(
  File "/opt/pysetup/.venv/lib/python3.10/site-packages/redis/client.py", line 1150, in _send_command_parse_response
    return self.parse_response(conn, command_name, **options)
  File "/opt/pysetup/.venv/lib/python3.10/site-packages/redis/client.py", line 1189, in parse_response
    response = connection.read_response()
  File "/opt/pysetup/.venv/lib/python3.10/site-packages/redis/connection.py", line 817, in read_response
    raise response
redis.exceptions.ResponseError: :__main__.Customer:index: no such index

db number set 0 then, no error

    class Meta:
-        database = get_redis_connection(host="redis", port=6379, db=1)
+        database = get_redis_connection(host="redis", port=6379, db=0)

result

[Customer(pk='01FTBDC0A8D47YQ516GQ84A8K8', first_name='Andrew', last_name='Brookins', email='[email protected]', join_date=datetime.date(2022, 1, 26), age=38, bio=None)]

Python 3.10.2
docker-compose version 1.29.2,
redis-om 0.0.17
module:name=ReJSON,ver=999999,api=1,filters=0,usedby=[search],using=[],options=[handle-io-errors]
module:name=search,ver=20206,api=1,filters=0,usedby=[],using=[ReJSON],options=[handle-io-errors]

Migrator using get_redis_connection

Hello, I'm trying to use Migrator with get_redis_connection like in the docs: https://redis.com/blog/introducing-redis-om-for-python/ but I'm facing this error, please help if you have an idea about it

In [11]: from redis_om import get_redis_connection

In [12]: get_redis_connection()
Out[12]: Redis<ConnectionPool<Connection<host=localhost,port=6379,db=0>>>

In [13]: Migrator(get_redis_connection()).run()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-13-00d45abb5072> in <module>
----> 1 Migrator(get_redis_connection()).run()

~/dev/redis-om-python-search-demo/venv/lib/python3.9/site-packages/redis_om/model/migrations/migrator.py in run(self)
    154         # TODO: Migration history
    155         # TODO: Dry run with output
--> 156         self.detect_migrations()
    157         for migration in self.migrations:
    158             migration.run()

~/dev/redis-om-python-search-demo/venv/lib/python3.9/site-packages/redis_om/model/migrations/migrator.py in detect_migrations(self)
     92         # Try to load any modules found under the given path or module name.
     93         if self.module:
---> 94             import_submodules(self.module)
     95 
     96         # Import this at run-time to avoid triggering import-time side effects,

~/dev/redis-om-python-search-demo/venv/lib/python3.9/site-packages/redis_om/model/migrations/migrator.py in import_submodules(root_module_name)
     22     """Import all submodules of a module, recursively."""
     23     # TODO: Call this without specifying a module name, to import everything?
---> 24     root_module = importlib.import_module(root_module_name)
     25 
     26     if not hasattr(root_module, "__path__"):

/usr/lib/python3.9/importlib/__init__.py in import_module(name, package)
    116     """
    117     level = 0
--> 118     if name.startswith('.'):
    119         if not package:
    120             msg = ("the 'package' argument is required to perform a relative "

AttributeError: 'Redis' object has no attribute 'startswith'

also how I can set the host of redis without using get_redis_connection if that possible

PrimaryKeyCreator, no parameter are passed to the create_pk method

I want to make an MurmurHash class to create a primary key for a new model instance.
I did this class that adheres to the PrimaryKeyCreator protocol:

# https://github.com/hajimes/mmh3
import mmh3

class Mmh3PrimaryKey:
    """
    A client-side generated primary key that follows the MurmurHash (MurmurHash3) spec.
    https://en.wikipedia.org/wiki/MurmurHash
    """

    @staticmethod
    def create_pk(self, *args, **kwargs) -> str:
        return str('some argument in args / kwargs')

and set Meta primary_key_creator_cls like this:

class ErrorServer(HashModel):
    local_hostname: str
    class Meta:
        primary_key_creator_cls = Mmh3PrimaryKey

But when I instantiate ErrorServerclass, no parameter (len of *args, **kwargs == 0) are passed to create_pk

es = ErrorServer(local_hostname='my_hostname', param2='Test')

JsonModel: find not working with dict

Hello,

In JsonModel, find not working with dict

Check out below code:

class Customer(JsonModel):
    name: str = Field(title="Name", index=True)
    metadata: dict[str, Any] = Field(title="Metadata")

Migrator().run()

c = Customer(name="Brookins", metadata={"extra": "option"}).save()
print("Customer Get: ", Customer.get(pk=c.pk))
print("Customer Find: ", Customer.find(Customer.name == "Brookins").all())

Results

Customer Get:  pk='01FRACMCBM9FE1MJSRCE4M3KP6' name='Brookins' metadata={'extra': 'option'}
Customer Find:  []

Optional field in a JSON model may cause indexing to fail

It appears that making a field optional in a JSON model may cause indexing of the resulting JSON to fail... example model - description field here causes indexing fails.

from pydantic import validator
from aredis_om import (Field, JsonModel, EmbeddedJsonModel)
from typing import List, Optional


class TaskAssignee(EmbeddedJsonModel):
    user_id: str = Field(index=True)


class Task(JsonModel):
    name: str = Field(index=True)
    status: str = Field(index=True)
    description: Optional[str] = Field(index=True, full_text_search=True)
    assigned_to: Optional[List[TaskAssignee]] = []
127.0.0.1:6379> ft.info :components.task.model.Task:index
 1) index_name
 2) :components.task.model.Task:index
...
 9) num_docs
10) "0"
...
37) hash_indexing_failures
38) "1"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.