redis / rueidis

A fast Golang Redis client that supports Client Side Caching, Auto Pipelining, Generics OM, RedisJSON, RedisBloom, RediSearch, etc.
Apache License 2.0
2.43k stars 154 forks source link

How to create multiple indexes on one repository #627

Closed hamidrabedi closed 2 months ago

hamidrabedi commented 2 months ago

This is the code im using and only creates the first index under the main index name which is: "jsonidx:workspace":

type JSONRepository struct {
    client     rueidis.Client
    repository om.Repository[Entity]
}

func NewJSONRepository(client rueidis.Client) *JSONRepository {
    repository := om.NewJSONRepository("workspace", Entity{}, client)
    repo := &JSONRepository{client: client, repository: repository}
    repo.CreateIndexes()
    return repo
}

var RediSearch *JSONRepository

func (r *JSONRepository) CreateIndexes() {
    if err := r.repository.CreateIndex(context.Background(), func(schema om.FtCreateSchema) rueidis.Completed {
        return schema.FieldName("$.user.name").As("name").Tag().Build()
    }); err != nil {
        logs.Warning(err)
    }
    if err := r.repository.CreateIndex(context.Background(), func(schema om.FtCreateSchema) rueidis.Completed {
        return schema.FieldName("$.user.owner").As("owner").Tag().Build()
    }); err != nil {
        logs.Warning(err)
    }
}

how to make is so it creates both indexes? I also have search, fetch and save functions that I want them to respect the indexes.

hamidrabedi commented 2 months ago

Like i wonder if there is a way to make this ORM to be smarter, so I add indexes on fields, it automatically adds those indexes and whenever I do searches on those fields it can do the call with the related index name. also when the index on that field does not exist, it can raise the error on application level.

rueian commented 2 months ago

Hi @hamidrabedi,

Multiple indexes are not supported and we have no roadmap for that because that will be extremely complicated and hard to get right.

You currently have to put all the fields you want to index into one CreateIndex, for example:

jsonRepo.CreateIndex(ctx, func(schema FtCreateSchema) rueidis.Completed {
    return schema.
        FieldName("$.id").As("id").Numeric().
        FieldName("$.loc").As("loc").Tag().
        FieldName("$.count").As("count").Numeric().Sortable().Build()
})

if there is a way to make this ORM to be smarter, so I add indexes on fields, it automatically adds those indexes

There must be a way to implement this feature but I believe it should not be the default behavior. Users need to explicitly enable the feature.

hamidrabedi commented 2 months ago

@rueian hello and thanks, this will do the trick for me.

I read the source code and still had no idea this is possible, a better documentation for om package would be nice.

tnx again.