search_syntax 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 8268b9b761eecbb0a430972682cfd5370b3b5b2d8598cdc327637e6351c9e700
4
+ data.tar.gz: c663d2e0eb50bf955c823fc5f02971e959c64bafb4202eb48551cb472fdae39f
5
+ SHA512:
6
+ metadata.gz: b50044490fa06cbec589163b8d60f7863160ba93579145a28ce6856bc9d7e2ac47cd02352842bfb3c533b3b4ccc8d80968683212dda3cf77e9d6835e98e1fbd4
7
+ data.tar.gz: 49d3c8c2b7d943afd75dd11bd255639178b1d3f926bca7c314b9d6d75f1eb7c50f3ee04508cc7ceb9cb1b62beb26f242c8113f4b4f2382d4254367fdf791da5a
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.1.2
data/.standard.yml ADDED
@@ -0,0 +1,4 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/testdouble/standard
3
+ ruby_version: 3.1
4
+
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at stereobooster@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in search_syntax.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "minitest", "~> 5.0"
11
+
12
+ gem "standard", "~> 1.3"
13
+
14
+ gem "treetop", "~> 1.6"
data/Gemfile.lock ADDED
@@ -0,0 +1,55 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ search_syntax (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.2)
10
+ json (2.6.2)
11
+ minitest (5.16.3)
12
+ parallel (1.22.1)
13
+ parser (3.1.2.1)
14
+ ast (~> 2.4.1)
15
+ polyglot (0.3.5)
16
+ rainbow (3.1.1)
17
+ rake (13.0.6)
18
+ regexp_parser (2.6.0)
19
+ rexml (3.2.5)
20
+ rubocop (1.35.1)
21
+ json (~> 2.3)
22
+ parallel (~> 1.10)
23
+ parser (>= 3.1.2.1)
24
+ rainbow (>= 2.2.2, < 4.0)
25
+ regexp_parser (>= 1.8, < 3.0)
26
+ rexml (>= 3.2.5, < 4.0)
27
+ rubocop-ast (>= 1.20.1, < 2.0)
28
+ ruby-progressbar (~> 1.7)
29
+ unicode-display_width (>= 1.4.0, < 3.0)
30
+ rubocop-ast (1.21.0)
31
+ parser (>= 3.1.1.0)
32
+ rubocop-performance (1.14.3)
33
+ rubocop (>= 1.7.0, < 2.0)
34
+ rubocop-ast (>= 0.4.0)
35
+ ruby-progressbar (1.11.0)
36
+ standard (1.16.1)
37
+ rubocop (= 1.35.1)
38
+ rubocop-performance (= 1.14.3)
39
+ treetop (1.6.11)
40
+ polyglot (~> 0.3)
41
+ unicode-display_width (2.3.0)
42
+
43
+ PLATFORMS
44
+ x86_64-darwin-20
45
+ x86_64-linux
46
+
47
+ DEPENDENCIES
48
+ minitest (~> 5.0)
49
+ rake (~> 13.0)
50
+ search_syntax!
51
+ standard (~> 1.3)
52
+ treetop (~> 1.6)
53
+
54
+ BUNDLED WITH
55
+ 2.3.12
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 stereobooster
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,103 @@
1
+ # search_syntax
2
+
3
+ Parser for "advanced search" query language. Inspired by [GitHub's search syntax](https://docs.github.com/en/search-github/getting-started-with-searching-on-github/understanding-the-search-syntax)
4
+
5
+ There is no wide accepted terminology for this kind of query language. Sometimes it's called: [query string](http://recursion.org/query-parser), [search query](https://tgvashworth.com/2016/06/27/twitter-search-query-parser.html), [advanced search query](https://github.com/mixmaxhq/search-string), [generic query](https://github.com/tomprogers/common-query-parser).
6
+
7
+ Package provides only parser. AST produced by parser can be converted to a specific "backend", for example: [ransack](https://activerecord-hackery.github.io/ransack/getting-started/search-matches/), [MySQL Full-Text Search](https://dev.mysql.com/doc/refman/8.0/en/fulltext-boolean.html), [PostgreSQL Full-Text Search](https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES), [Meilisearch](https://docs.meilisearch.com/reference/api/search.html#body), [Elasticsearch](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html), [Solr](https://solr.apache.org/guide/6_6/the-standard-query-parser.html), [Lucene](https://lucene.apache.org/core/2_9_4/queryparsersyntax.html) ([Lucene vs Solr](https://www.lucenetutorial.com/lucene-vs-solr.html)), [Sphinx](https://sphinxsearch.com/docs/current/extended-syntax.html).
8
+
9
+ Transforming AST is out of scope of this package, except for Ransack, which serves as an example of implementation.
10
+
11
+ ## Disclaimer
12
+
13
+ So far parser only supports bare strings, **quoted strings** (`"some string"`) and parameters (`param:1`).
14
+
15
+ Parser **doesn't** support negation (`not`/`-`), boolean operations (`and`/`&`/`or`/`|`) and groupping (`(a | b)`).
16
+
17
+ This probably will change as soon as I understand how to add those "advanced" features without making it less user-friendly to non-techy people. See "Challenge" section for explantions.
18
+
19
+ ## Challenge
20
+
21
+ Main challenge is to come up with query language intuitive enough that non-techy people can use, but powerfull enough to expose all advanced features.
22
+
23
+ There are different types of search, they require different features:
24
+
25
+ ```mermaid
26
+ graph LR
27
+ Search --> Parametric --> op1[param = 1, param > 2, etc.]
28
+ Search --> s1[Text: single term]
29
+ s1 --> op2[Phonetic similarity: names, emails, words with alternate spellings, etc.]
30
+ s1 --> op3[Ortographic similarity: drug names, biological species, typos in proper nouns, etc.]
31
+ s1 --> op4[Pattern match: logs, match by part of word, etc.]
32
+ Search --> s2[Text: multiple terms]
33
+ s2 --> op5[Full-text search: text in natural language]
34
+ s2 --> op6[Single term search with boolean operations: AND, OR, NOT, grouping]
35
+ ```
36
+
37
+ **Note**: No. Full-text search is not an universal solution for all types of text search. It is designed to search in natural language texts. But this subject deserves a separate article.
38
+
39
+ **Parametric search** aka faceted search - [filter by strctured data](https://en.wikipedia.org/wiki/Faceted_search).
40
+
41
+ **Aproximate search** aka fuzzy search aka approximate string matching - [is the technique of finding strings that match a pattern approximately (rather than exactly)](https://en.wikipedia.org/wiki/Approximate_string_matching).
42
+
43
+ ## Installation
44
+
45
+ Install the gem and add to the application's Gemfile by executing:
46
+
47
+ ```sh
48
+ $ bundle add search_syntax
49
+ ```
50
+
51
+ If bundler is not being used to manage dependencies, install the gem by executing:
52
+
53
+ ```sh
54
+ $ gem install search_syntax
55
+ ```
56
+
57
+ ## Usage
58
+
59
+ ### With ransack
60
+
61
+ ```diff
62
+ def index
63
+ - @q = Person.ransack(params[:q])
64
+ + query_parser = SearchSyntax::Ransack.new(text: :name_or_email_cont, params: Person.column_names - ["id"])
65
+ + @q = Person.ransack(query_parser.parse(params[:search]))
66
+ @people = @q.result(distinct: true)
67
+ end
68
+ ```
69
+
70
+ ### Standalone
71
+
72
+ see `lib/search_syntax/ransack.rb` for an example of how to use parser
73
+
74
+ ## Similar packages
75
+
76
+ - [search_cop](https://github.com/mrkamel/search_cop)
77
+ - [easy-filter](https://github.com/Noriller/easy-filter)
78
+ - [human-ql](https://github.com/dekellum/human-ql)
79
+ - [logical_query_parser](https://github.com/kanety/logical_query_parser)
80
+
81
+ ## Development
82
+
83
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
84
+
85
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
86
+
87
+ To regenrate parser
88
+
89
+ ```sh
90
+ $ bin/tt lib/search_syntax/search_syntax_grammar.tt
91
+ ```
92
+
93
+ ## Contributing
94
+
95
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/search_syntax. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/search_syntax/blob/master/CODE_OF_CONDUCT.md).
96
+
97
+ ## License
98
+
99
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
100
+
101
+ ## Code of Conduct
102
+
103
+ Everyone interacting in the SearchSyntax project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/search_syntax/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/test_*.rb"]
10
+ end
11
+
12
+ require "standard/rake"
13
+
14
+ task default: %i[test standard]
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SearchSyntax
4
+ class DuplicateParamError < StandardError
5
+ attr_reader :name, :start, :finish
6
+
7
+ def initialize(name:, start:, finish:)
8
+ @name = name
9
+ @start = start
10
+ @finish = finish
11
+
12
+ super("Duplicate parameter '#{name}' at position #{start}.")
13
+ end
14
+ end
15
+
16
+ class UnknownParamError < StandardError
17
+ attr_reader :name, :start, :finish, :did_you_mean
18
+
19
+ def initialize(name:, start:, finish:, did_you_mean:)
20
+ @name = name
21
+ @start = start
22
+ @finish = finish
23
+ @did_you_mean = did_you_mean
24
+
25
+ message = "Unknown parameter '#{name}' at position #{start}."
26
+ if did_you_mean[0]
27
+ message += " Did you mean '#{did_you_mean[0]}'?"
28
+ end
29
+
30
+ super(message)
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "treetop/runtime"
4
+ require_relative "search_syntax_grammar"
5
+
6
+ module SearchSyntax
7
+ class Parser < ::SearchSyntaxGrammarParser
8
+ end
9
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "ransack_transformer"
4
+
5
+ module SearchSyntax
6
+ class Ransack
7
+ # text - symbol. Idea for the future: it can be callback to allow to manipulate query for full-text search
8
+ # params - array of strings
9
+ # sort - string. nil - to disbale parsing sort param
10
+ def initialize(text:, params:, sort: nil)
11
+ @transformer = RansackTransformer.new(text: text, params: params, sort: sort)
12
+ @parser = Parser.new
13
+ end
14
+
15
+ def parse_with_errors(text)
16
+ @transformer.transform_with_errors(@parser.parse(text || "").value)
17
+ end
18
+
19
+ def parse(text)
20
+ parse_with_errors(text)[0]
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SearchSyntax
4
+ class RansackTransformer
5
+ PREDICATES = {
6
+ ">=": :gteq,
7
+ "=>": :gteq,
8
+ "<=": :lteq,
9
+ "=<": :lteq,
10
+ "!=": :not_eq,
11
+ ">": :gt,
12
+ "<": :lt
13
+ # in, not_in, present, blank, null, not_null,
14
+ # matches, does not match, cont, cont_any, cont_all,
15
+ # i_cont..., start, end, true, false, not_true, not_false
16
+ }
17
+
18
+ def initialize(text:, params:, sort: nil)
19
+ @text = text
20
+ @params = params
21
+ @sort = sort
22
+ @spell_checker = DidYouMean::SpellChecker.new(dictionary: @params)
23
+ end
24
+
25
+ def transform_sort_param(value)
26
+ value.split(",").map do |sort_value|
27
+ if sort_value.start_with?("-")
28
+ "#{sort_value[1..]} desc"
29
+ else
30
+ "#{sort_value} asc"
31
+ end
32
+ end
33
+ end
34
+
35
+ def transform_with_errors(ast)
36
+ errors = []
37
+ result = {}
38
+
39
+ if @params.is_a?(Array)
40
+ ast = ast.filter do |node|
41
+ if node[:type] != :param
42
+ true
43
+ elsif node[:name] == @sort
44
+ result[:s] = transform_sort_param(node[:value])
45
+ false
46
+ elsif @params.include?(node[:name])
47
+ predicate = PREDICATES[node[:predicate]] || :eq
48
+ key = "#{node[:name]}_#{predicate}".to_sym
49
+ if !result.key?(key)
50
+ result[key] = node[:value]
51
+ else
52
+ errors.push(DuplicateParamError.new(
53
+ name: node[:name],
54
+ start: node[:start],
55
+ finish: node[:finish]
56
+ ))
57
+ end
58
+ false
59
+ else
60
+ errors.push(UnknownParamError.new(
61
+ name: node[:name],
62
+ start: node[:start],
63
+ finish: node[:finish],
64
+ did_you_mean: @spell_checker.correct(node[:name])
65
+ ))
66
+ true
67
+ end
68
+ end
69
+ end
70
+
71
+ previous = -1
72
+ result[@text] = ast.map do |node|
73
+ separator = previous == node[:start] || previous == -1 ? "" : " "
74
+ previous = node[:finish]
75
+ separator + node[:raw]
76
+ end.join
77
+
78
+ [result, errors]
79
+ end
80
+ end
81
+ end