typesense-php icon indicating copy to clipboard operation
typesense-php copied to clipboard

Analytics rules offsetExists, strange behavior

Open sas-adilis opened this issue 8 months ago • 4 comments

Hi everyone, I'm having a strange problem with the library, maybe I'm using it wrong.

When i try this :

$ruleExists = $client->analytics->rules()->offsetExists($ruleCollectionName);

It return false, $analyticsRules is empty

But if i do this

$ruleExists = false;
foreach ($rules['rules'] as $rule) {
    if ($rule['name'] == $ruleCollectionName) {
        $ruleExists = true;
        break;
    }
}

It returns true. I'm on PHP 8.4

Thank you

sas-adilis avatar May 01 '25 05:05 sas-adilis

If you try to access it directly, if it doesn't exist, the client will instantiate a new object for it, so it is working as designed. May I know the use-case for this?

tharropoulos avatar May 01 '25 16:05 tharropoulos

It comes up often with users using the local in-memory instance about collections / analytics rules etc to access remote, real Typesense entities, leading to confusion. If you want to check for the real analytics rule in your Typesense server, you can use the real analytics rules:

// First, retrieve all rules from API
$rules = $client->analytics->rules()->retrieve();


$ruleExists = false;
foreach ($rules['rules'] as $rule) {
    if ($rule['name'] == $ruleCollectionName) {
        $ruleExists = true;
        break;
    }
}

If your use-case differs to what I'm describing, could you give a little bit more context so we can pinpoint how to solve your problem?

tharropoulos avatar May 02 '25 06:05 tharropoulos

@tharropoulos is this also the case for \Typesense\Keys::offsetExists?

I'm noticing similar behavior. $keys->offsetExists(30000); always returns false. I'm running a script from my local environment to delete old search keys in our production environment.

I was ready to create a new issue for it but I re-read this issue a couple of times and you are suggesting that this is expected behavior? I don't need offsetExists anymore because I got around it but I was miffed that it didn't do what I expected it to.

breadthe avatar Nov 13 '25 19:11 breadthe

The issue in the original post is that the in-memory object will instantiate the children objects whether or not they exist in the remote Typesense instance.

They don't directly call out to the API, to avoid any potential slow requests / unintended behavior, but are meant for in-memory access of the objects, entirely focused on PHP objects

tharropoulos avatar Nov 17 '25 09:11 tharropoulos