Multi-language indexes with Laravel Scout and Algolia

混江龙づ霸主 提交于 2019-12-03 13:28:30

I thought about it a lot and I think the best way would be to use 1 index per model and take advandate of the callback you can pass to ::search()

Indexing data

First you need to use toSearchableArray() to prepare the data. I would unset every unnecessary attributes (like dates) then nest content under its ISO.

{
  objectID: 1,
  en: {
    title: "Title in english",
    body: "trucated body in english"
  },
  fr: {
    title: "Titre en français",
    body: "contenu tronqué en français"
  }
}

Please note that Algolia has a limit of 10KB per records. The best way to handle this is to truncate your biggest attributes. Don't worry, it doesn't impact relevance. If you miss the second half of your article, usually all the relevant content is already in the first haft.

Setup Algolia config in dashboard

Then head to your dashboard and add fr and en to the searchableAttributes.

Search

You can restrict searchableAttributes at query time with a callback passed to the search

$lang = 'en';
Model::search($query, function ($algolia, $query, $options) use ($lang) {
    $options = array_merge($options, [
        'restrictSearchableAttributes' => [$lang],
    ]);

    return $algolia->search($query, $options);
});

I created a trait to achieve something similar. Maybe you can do something similar, in order to have a easy-to-use syntax like:

Model::searchLang($lang, $query);

After all the thinking, I really think it's the least hacky way to use Laravel Scout with your constraints.

Please let me know what you think :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!