How do I implement advanced search with operators with pg_search?
Asked Answered
P

1

10

I have implemented PgSearch on my Node model like so:

include PgSearch
pg_search_scope :node_search, against: [:name, :user_id, :circa],
    using: { tsearch: { any_word: true} },
    :associated_against => {
      comments: [:message],
      user: [:first_name, :last_name, :email],
      memberships: [:relation]
    }

And in my controller I have this:

if params[:search]
  @nodes = Node.node_search(params[:search])
end

Ideally, what I would like to be able to do though, is have someone be able to type in the text representation (a flag) of one of the associations and have the search filter just on that flag.

E.g. say: "name: Bouncing Ball", where the search would take place just on the column called name on the nodes model. Aka...it would look for all the nodes with the name Bouncing Ball and not search other columns or models or even any of the associations.

Naturally, I would like to be able to do searches like: owner: John Brown (which searches for all nodes whose owner/user first_name and last_name are John Brown), comment: Manhattan (which searches for all nodes that have a comment with the text Manhattan in the copy, and so on.

How do I achieve this with PgSearch?

Pittel answered 26/5, 2015 at 23:48 Comment(3)
Can you not do this in the controller, with a regex/string manipulation? For instance just check if 'owner:' exists as part of params[:search], and then just use some conditional logic?Speleology
@OliverM that sounds interesting. Can you show me a code example. Thanks!Pittel
Although this seems interesting, but I really doubt that it would affect the performance at all... ( under the assumption that all the columns you search in are properly indexed). I know you didn't mention anything about performance and you most properly need this to filter results only...Retrogression
X
4

Have you tried to use a combinations of "Dynamic search scopes" with some controller processing of the search string?

name: Bob, parse out the columns/relationship and the searching value then pass it to a pg_search_scope with a lambda block?

Xhosa answered 29/5, 2015 at 14:38 Comment(1)
Can you show me some example code, because I can't quite grok it.Pittel

© 2022 - 2024 — McMap. All rights reserved.