af2e13e48be4640691032d9252aabdc184e33944
[akkoma] / lib / pleroma / search / elasticsearch.ex
1 defmodule Pleroma.Search.Elasticsearch do
2 @behaviour Pleroma.Search
3
4 alias Pleroma.Web.MastodonAPI.StatusView
5
6 defp to_es(term) when is_binary(term) do
7 %{
8 match: %{
9 content: %{
10 query: term,
11 operator: "AND"
12 }
13 }
14 }
15 end
16
17 defp to_es({:quoted, term}), do: to_es(term)
18
19 defp to_es({:filter, ["hashtag", query]}) do
20 %{
21 term: %{
22 hashtags: %{
23 value: query
24 }
25 }
26 }
27 end
28
29 defp to_es({:filter, [field, query]}) do
30 %{
31 term: %{
32 field => %{
33 value: query
34 }
35 }
36 }
37 end
38
39 defp parse(query) do
40 query
41 |> SearchParser.parse!()
42 |> Enum.map(&to_es/1)
43 end
44
45 @impl Pleroma.Search
46 def search(%{assigns: %{user: user}} = _conn, %{q: query} = _params, _options) do
47 q = %{
48 query: %{
49 bool: %{
50 must: parse(query)
51 }
52 }
53 }
54
55 out = Pleroma.Elasticsearch.search_activities(q)
56
57 with {:ok, raw_results} <- out do
58 results =
59 raw_results
60 |> Map.get(:body, %{})
61 |> Map.get("hits", %{})
62 |> Map.get("hits", [])
63 |> Enum.map(fn result -> result["_id"] end)
64 |> Pleroma.Activity.all_by_ids_with_object()
65
66 %{
67 "accounts" => [],
68 "hashtags" => [],
69 "statuses" =>
70 StatusView.render("index.json",
71 activities: results,
72 for: user,
73 as: :activity
74 )
75 }
76 end
77 end
78 end