1<?php
2
3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
4// See the LICENCE file in the repository root for full licence text.
5
6namespace App\Models\Traits\Es;
7
8use App\Libraries\Elasticsearch\Es;
9use DateTime;
10
11trait BaseIndexable
12{
13 abstract public static function esIndexName();
14
15 abstract public static function esSchemaFile();
16
17 public static function esCreateIndex(string $name = null)
18 {
19 // TODO: allow overriding of certain settings (shards, replicas, etc)?
20 $params = [
21 'index' => $name ?? static::esIndexName(),
22 'body' => static::esSchemaConfig(),
23 ];
24
25 return Es::getClient()->indices()->create($params);
26 }
27
28 public static function esMappings()
29 {
30 return static::esSchemaConfig()['mappings']['properties'];
31 }
32
33 public static function esSchemaConfig()
34 {
35 static $schema;
36 if (!isset($schema)) {
37 $schema = json_decode(file_get_contents(static::esSchemaFile()), true);
38 }
39
40 return $schema;
41 }
42
43 public static function esTimestampedIndexName(?DateTime $time = null)
44 {
45 return static::esIndexName().'_'.($time ?? now())->format('YmdHis');
46 }
47}