b5a394e34929821f87ec931c406cb04c6fa5dc16
[akkoma] / lib / mix / tasks / pleroma / search / meilisearch.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Mix.Tasks.Pleroma.Search.Meilisearch do
6 require Logger
7 require Pleroma.Constants
8
9 import Mix.Pleroma
10 import Ecto.Query
11
12 def run(["index"]) do
13 start_pleroma()
14
15 endpoint = Pleroma.Config.get([Pleroma.Search.Meilisearch, :url])
16
17 {:ok, _} =
18 Pleroma.HTTP.post(
19 "#{endpoint}/indexes/objects/settings/ranking-rules",
20 Jason.encode!([
21 "desc(published)",
22 "typo",
23 "words",
24 "proximity",
25 "attribute",
26 "wordsPosition",
27 "exactness"
28 ])
29 )
30
31 {:ok, _} =
32 Pleroma.HTTP.post(
33 "#{endpoint}/indexes/objects/settings/searchable-attributes",
34 Jason.encode!([
35 "content"
36 ])
37 )
38
39 chunk_size = 10_000
40
41 Pleroma.Repo.transaction(
42 fn ->
43 Pleroma.Repo.stream(
44 from(Pleroma.Object,
45 # Only index public posts which are notes and have some text
46 where:
47 fragment("data->>'type' = 'Note'") and
48 fragment("LENGTH(data->>'content') > 0") and
49 fragment("data->'to' \\? ?", ^Pleroma.Constants.as_public()),
50 order_by: [desc: fragment("data->'published'")]
51 ),
52 timeout: :infinity
53 )
54 |> Stream.map(&Pleroma.Search.Meilisearch.object_to_search_data/1)
55 |> Stream.filter(fn o -> not is_nil(o) end)
56 |> Stream.chunk_every(chunk_size)
57 |> Stream.transform(0, fn objects, acc ->
58 new_acc = acc + Enum.count(objects)
59
60 IO.puts("Indexed #{new_acc} entries")
61
62 {[objects], new_acc}
63 end)
64 |> Stream.each(fn objects ->
65 {:ok, result} =
66 Pleroma.HTTP.post(
67 "#{endpoint}/indexes/objects/documents",
68 Jason.encode!(objects)
69 )
70
71 if not Map.has_key?(Jason.decode!(result.body), "updateId") do
72 IO.puts("Failed to index: #{result}")
73 end
74 end)
75 |> Stream.run()
76 end,
77 timeout: :infinity
78 )
79 end
80
81 def run(["clear"]) do
82 start_pleroma()
83
84 endpoint = Pleroma.Config.get([Pleroma.Search.Meilisearch, :url])
85
86 {:ok, _} =
87 Pleroma.HTTP.request(:delete, "#{endpoint}/indexes/objects/documents", "", [],
88 timeout: :infinity
89 )
90 end
91 end