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.

1 like

I believe Discourse has always grouped results by topics, since its first release, and it’s intentional because Discourse is a topic-based system. If the first topic has 20 matching posts, the next relevant topic could show up as result 21 instead of result 2. That would be frustrating if the first topic is not what you’re looking for.

There is another way around this beyond using “most liked,” you can add in:all-posts to your search.