Skip to content

Commit

Permalink
tec: Add a GIN index on links.tags
Browse files Browse the repository at this point in the history
  • Loading branch information
marienfressinaud committed Oct 31, 2024
1 parent 54c5297 commit 4faef23
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace App\migrations;

class Migration202410310001ChangeLinksTagsFromJsonToJsonb
{
public function migrate(): bool
{
$database = \Minz\Database::get();

$database->exec(<<<'SQL'
ALTER TABLE links
ALTER COLUMN tags
SET DATA TYPE JSONB
USING tags::jsonb;
CREATE INDEX idx_links_tags ON links USING GIN (tags);
SQL);

return true;
}

public function rollback(): bool
{
$database = \Minz\Database::get();

$database->exec(<<<'SQL'
DROP INDEX idx_links_tags;
ALTER TABLE links
ALTER COLUMN tags
SET DATA TYPE JSON
USING tags::json;
SQL);

return true;
}
}
3 changes: 2 additions & 1 deletion src/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ CREATE TABLE links (
url_replies TEXT NOT NULL DEFAULT '',
reading_time INTEGER NOT NULL DEFAULT 0,
image_filename TEXT,
tags JSON NOT NULL DEFAULT '[]',
tags JSONB NOT NULL DEFAULT '[]',

to_be_fetched BOOLEAN NOT NULL DEFAULT true,
fetched_at TIMESTAMPTZ,
Expand All @@ -173,6 +173,7 @@ CREATE INDEX idx_links_url ON links USING gin (url gin_trgm_ops);
CREATE INDEX idx_links_to_be_fetched ON links(to_be_fetched) WHERE to_be_fetched = true;
CREATE INDEX idx_links_image_filename ON links(image_filename) WHERE image_filename IS NOT NULL;
CREATE INDEX idx_links_search ON links USING GIN (search_index);
CREATE INDEX idx_links_tags ON links USING GIN (tags);

CREATE TABLE links_to_collections (
id BIGSERIAL PRIMARY KEY,
Expand Down
4 changes: 2 additions & 2 deletions src/search_engine/LinksSearcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -191,12 +191,12 @@ private static function buildWhereQuery(Query $query): array

if ($tags_parameters) {
$tags_statement = implode(',', $tags_parameters);
$where_sql .= " AND l.tags::jsonb ??& array[{$tags_statement}]";
$where_sql .= " AND l.tags ??& array[{$tags_statement}]";
}

if ($not_tags_parameters) {
$not_tags_statement = implode(',', $not_tags_parameters);
$where_sql .= " AND NOT (l.tags::jsonb ??| array[{$not_tags_statement}])";
$where_sql .= " AND NOT (l.tags ??| array[{$not_tags_statement}])";
}

return [$where_sql, $parameters];
Expand Down

0 comments on commit 4faef23

Please sign in to comment.