Search based on multiple index

Hi,
I have an index for ‘Posts’ & another for ‘Connections’
A user can have multiple users as connections.
A user can create multiple posts, similar to facebook.
I need a search on ‘Post’ which will return posts made by an user’s connection.
How can i achieve that?

Hello,

Algolia doesn’t store relationships between several types of data, but what you can do, is this structure:

  • 1 posts index
  • 1 users index

Every time you save a post, you add the objectId of the user that made that post as a tag. Then you can add the tagFilters field as default refinement for that objectId, so that you’ll only get results for that user.

Does that help you?

Can this be done via laravel scout?

Hi Driapham,

I assume you’re using InstantSearch so I’m only covering the indexing part.

We want to had the user_id of each connection inside a post, then filter each results by current user id.

You have to override toSearchableArray() method in your post model: https://laravel.com/docs/5.5/scout#configuring-searchable-data

Should be something like

public function toSearchableArray()
{
    $record = $this->toArray();

    $record['_tags'] = $this->getAllConnectionIds();

    return $record;
}

Then you will need to dispatch an event when a new user connection is created and an event listener to reindex all necessary posts. Or you can run a full reindex every night.

1 Like

you mean the tagFilters will have an array of all the user’s connections? this means every time a new connection is added, i’ll have to reindex the Posts as well right?

That’s right, you should consider the Algolia index as a snapshot of the connections at a certain time. As @julienbourdeau can probably confirm for me, I think that Laravel Scout will automatically reindex if another connection changes

Thanks… will try it out

Unfortunately, Scout will reindex all connection when a Post change. Scout is unaware that post and connection are related.

That’s why you need to define your own event in case of new connection and reindex related post. You can selec the post correct post collection and call searchable() on it.

Post::where(.....)->searchable();