Search Results Differ by Sort Order

After user complaints, I noticed that search results do not include all posts containing the search terms. I found this from 2018 mentioning that sorting by ‘Most Liked’ does return all posts, which I can confirm is still the case.

This behavior is unexpected, and seems unintended. There is no option to change this behavior, nothing in the docs about it, and nothing in the UI suggests that search results have been omitted.

From /lib/search.rb:

def aggregate_post_sql(opts)
    ...
    query =
      if @order == :likes
        # likes are a pain to aggregate so skip
        posts_query(limit, type_filter: opts[:type_filter]).select("topics.id", "posts.post_number")
      else
        posts_query(limit, aggregate_search: true, type_filter: opts[:type_filter]).select(
          "topics.id",
          "#{min_or_max}(posts.post_number) post_number",
        ).group("topics.id")
      end
      ...
end

This is the only place where ‘Most Liked’ is clearly treated differently from other search orderings, so it’s probably the root cause.

It looks like aggregate_search is intended to be applied when a search should return topics instead of posts, but it’s being applied to all searches unless sorted by likes.