Implementing Google Search Operators

Google currently uses keywords such as site: or is: in search (second example from Gmail). I am trying to develop a similar system, and I am wondering how best to determine the identification and processing of these conditions. For simplicity, suppose that the OO language is used (Ruby, Python, Java, C #, etc.).

My current plan is to have a separate class for each keyword. These classes have a priority value and three methods:

  • isRelevant(String searchPhrase) : returns true if the search phrase matches the class filter.
  • getResults(String searchPhrase) : returns a list of results based on a search phrase.
  • reviseSearch(String searchPhrase) : returns the modified version of the search phrase. This will usually remove the match to avoid reprocessing by the instance with a lower priority, but may also add text or clear the line completely.

Then, the calling method will go through these keyword filters until the search phrase is empty or there are no more filters (in the latter case, it returns to normal search behavior).

So the question is: is this the most efficient way to do this, or is there an even more suitable method? Some details still need to be clarified, but is this a step in the right direction?

+3
source share
1 answer

The basics

sample string:

foo:(hello world) bar:(-{bad things}) email: something@email.tld another:weird characters +=2{-52!%#^ final:end

split with regex:

/\s+(?=\w+:)/

return array:

 [ 'foo:(hello world)', 'bar:(-{bad things})', 'email: something@email.tld ', 'another:weird characters +=2{-52!%#^', 'final:end' ] 

explanation:

 \s+ one or more spaces (?= followed by (positive lookahead) \w+ one or more word characters : literal `:' (colon character) ) 

Using:

Let's go through the array, divide each element into : (colon). The left side of key can be used to call the function, and the right side of value can be passed as a parameter to the function. This should pretty much put you on the path for what you want to do from here.

Ruby example

search.rb

 # Search class class Search def initialize(query) @query = query end def foo(input) "foo has #{input}" end def bar(input) "bar has #{input}" end def email(input) "email has #{input}" end def another(input) "another has #{input}" end def final(input) "final has #{input}" end def exec @query.split(/\s+(?=\w+:)/).each do |e| method, arg = e.split(/:/) puts send(method, arg) if respond_to? method end end end 

use search.rb

 q = "foo:(hello world) bar:(-{bad things}) email: something@email.tld another:weird characters +=2{-52!%#^ final:end"; s = Search.new(q) s.exec 

Exit

 foo has (hello world) bar has (-{bad things}) email has something@email.tld another has weird characters +=2{-52!%#^ final has end 
+6
source

Source: https://habr.com/ru/post/1412553/


All Articles