archsight 0.5.7 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/docs/pages.md +2 -2
- data/docs/search.md +91 -17
- data/lib/archsight/database.rb +14 -0
- data/lib/archsight/diagram/style/representers.rb +3 -1
- data/lib/archsight/linter.rb +8 -5
- data/lib/archsight/mcp/query_hints.rb +0 -23
- data/lib/archsight/mcp/query_tool.rb +15 -12
- data/lib/archsight/query/ast.rb +46 -2
- data/lib/archsight/query/evaluator.rb +7 -1
- data/lib/archsight/query/full_text.rb +69 -0
- data/lib/archsight/query/parser.rb +43 -4
- data/lib/archsight/query/text_search.rb +2 -12
- data/lib/archsight/query.rb +25 -4
- data/lib/archsight/resources/config.rb +21 -0
- data/lib/archsight/text_index/expression.rb +73 -0
- data/lib/archsight/text_index/matcher.rb +107 -0
- data/lib/archsight/text_index/snippets.rb +107 -0
- data/lib/archsight/text_index/weights.rb +76 -0
- data/lib/archsight/text_index.rb +89 -0
- data/lib/archsight/version.rb +1 -1
- data/lib/archsight/web/api/json_helpers.rb +23 -4
- data/lib/archsight/web/api/openapi/spec.yaml +70 -0
- data/lib/archsight/web/api/routes.rb +7 -3
- data/lib/archsight/web/application.rb +14 -1
- data/lib/archsight/web/public/vue/{DocPage-BHffBQ3u.js → DocPage-qVqx-gJ9.js} +1 -1
- data/lib/archsight/web/public/vue/{EditorPage-BHZtvtnN.js → EditorPage-Bz21Jreq.js} +1 -1
- data/lib/archsight/web/public/vue/{ErrorPage-BQARAwF8.js → ErrorPage-CKNxpjzn.js} +1 -1
- data/lib/archsight/web/public/vue/{GraphView-D84CH00D.js → GraphView-6EzYwP8T.js} +1 -1
- data/lib/archsight/web/public/vue/{HomePage-BJpTPWFz.js → HomePage-tCk9Pmh5.js} +2 -2
- data/lib/archsight/web/public/vue/{InstanceRouter-C1Da3nWo.js → InstanceRouter-BQx8UnCA.js} +1 -1
- data/lib/archsight/web/public/vue/{KindList-DNRUVuEJ.js → KindList-Ky5uk5xe.js} +1 -1
- data/lib/archsight/web/public/vue/{PageView-DzKj212I.js → PageView-AdolhVA0.js} +1 -1
- data/lib/archsight/web/public/vue/{QueryError-CTVAL1Tm.js → QueryError-Qt-3lwb7.js} +1 -1
- data/lib/archsight/web/public/vue/ResourceList-LYEUNwQn.css +1 -0
- data/lib/archsight/web/public/vue/ResourceList-zb7VO6Bk.js +2 -0
- data/lib/archsight/web/public/vue/SearchResults-8SgERqBf.js +1 -0
- data/lib/archsight/web/public/vue/SearchResults-C8Nqi4yk.css +1 -0
- data/lib/archsight/web/public/vue/{WikiPage-DSEL2gmd.js → WikiPage-D0x1B2aR.js} +1 -1
- data/lib/archsight/web/public/vue/{index-JZkWwfYg.js → index-DlL2S_4s.js} +2 -2
- data/lib/archsight/web/public/vue.html +1 -1
- metadata +36 -16
- data/lib/archsight/web/public/vue/ResourceList-CRt_FpfS.js +0 -2
- data/lib/archsight/web/public/vue/ResourceList-D75O87zG.css +0 -1
- data/lib/archsight/web/public/vue/SearchResults-BMwBz4BB.js +0 -1
- data/lib/archsight/web/public/vue/SearchResults-BV6UHriJ.css +0 -1
data/lib/archsight/query.rb
CHANGED
|
@@ -10,6 +10,7 @@ require_relative "query/lexer"
|
|
|
10
10
|
require_relative "query/parser"
|
|
11
11
|
require_relative "query/text_search"
|
|
12
12
|
require_relative "query/evaluator"
|
|
13
|
+
require_relative "text_index"
|
|
13
14
|
|
|
14
15
|
module Archsight
|
|
15
16
|
module Query
|
|
@@ -17,8 +18,10 @@ module Archsight
|
|
|
17
18
|
class Query
|
|
18
19
|
attr_reader :source, :ast
|
|
19
20
|
|
|
20
|
-
|
|
21
|
+
# @param bare_words [Symbol] :name (default) or :search, see Parser
|
|
22
|
+
def initialize(source, bare_words: :name)
|
|
21
23
|
@source = source
|
|
24
|
+
@bare_words = bare_words
|
|
22
25
|
@ast = parse(source)
|
|
23
26
|
end
|
|
24
27
|
|
|
@@ -34,6 +37,24 @@ module Archsight
|
|
|
34
37
|
evaluator.filter(@ast)
|
|
35
38
|
end
|
|
36
39
|
|
|
40
|
+
# The matching instances ordered by relevance when the query searches text (full-text conditions, search box
|
|
41
|
+
# words), else as #filter returns them
|
|
42
|
+
def ranked(database)
|
|
43
|
+
evaluator = Evaluator.new(database)
|
|
44
|
+
evaluator.rank(@ast, evaluator.filter(@ast))
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# [[instance, relevance]] best first when the query searches text, nil otherwise
|
|
48
|
+
def scored(database)
|
|
49
|
+
evaluator = Evaluator.new(database)
|
|
50
|
+
evaluator.scored(@ast, evaluator.filter(@ast))
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Whether the order of #ranked is a relevance order (the query searches text)
|
|
54
|
+
def ranked?
|
|
55
|
+
!FullText.ranking_nodes(@ast).empty?
|
|
56
|
+
end
|
|
57
|
+
|
|
37
58
|
# Return the kind filter if present (for optimization)
|
|
38
59
|
def kind_filter
|
|
39
60
|
@ast.kind_filter
|
|
@@ -53,7 +74,7 @@ module Archsight
|
|
|
53
74
|
def parse(source)
|
|
54
75
|
lexer = Lexer.new(source)
|
|
55
76
|
tokens = lexer.tokenize
|
|
56
|
-
parser = Parser.new(tokens, source: source)
|
|
77
|
+
parser = Parser.new(tokens, source: source, bare_words: @bare_words)
|
|
57
78
|
parser.parse
|
|
58
79
|
rescue LexerError, ParseError, InvalidRegexError => e
|
|
59
80
|
# Re-raise with source context
|
|
@@ -62,8 +83,8 @@ module Archsight
|
|
|
62
83
|
end
|
|
63
84
|
|
|
64
85
|
# Convenience method for creating queries
|
|
65
|
-
def self.parse(source)
|
|
66
|
-
Query.new(source)
|
|
86
|
+
def self.parse(source, bare_words: :name)
|
|
87
|
+
Query.new(source, bare_words: bare_words)
|
|
67
88
|
end
|
|
68
89
|
end
|
|
69
90
|
end
|
|
@@ -25,6 +25,7 @@ class Archsight::Resources::Config < Archsight::Resources::Base
|
|
|
25
25
|
|---------------|----------|---------|
|
|
26
26
|
| `pdf` | `pdf/*`: colours, fonts, logo, header and footer | [PDF export](/doc/pdf-export) |
|
|
27
27
|
| `summary` | `summary/lens-<layer>`: what the MCP `summary` tool follows per layer | MCP `summary` tool |
|
|
28
|
+
| `search` | `search/weight-<layer>`: how much a hit of a layer or kind counts in a text search | [Search](/doc/search) |
|
|
28
29
|
|
|
29
30
|
A document picks a different Config of the type with the tag `pdf:template:<name>`; without a tag the one named
|
|
30
31
|
`default` is used, and without any the export has a neutral built-in look.
|
|
@@ -47,6 +48,19 @@ class Archsight::Resources::Config < Archsight::Resources::Base
|
|
|
47
48
|
out servedBy depth=2: Runs on
|
|
48
49
|
```
|
|
49
50
|
|
|
51
|
+
## Search weights
|
|
52
|
+
|
|
53
|
+
A text search (the words in the search box, `text: "..."`) orders its hits by relevance times the weight of their
|
|
54
|
+
kind. Built in: `Page` 3, `ApplicationService` and `ApplicationComponent` 2, `ApplicationInterface` and the layer
|
|
55
|
+
`application` 1.5, `business`, `strategy` and `motivation` 1.2, `technology` and `implementation` 1, `other` 0.5.
|
|
56
|
+
A Config of type `search` (the one named `default`) sets a layer with `search/weight-<layer>` and a single kind
|
|
57
|
+
with `search/weight-<Kind>`, numbers from 0 to 100. What the Config says comes first, the kind before the layer:
|
|
58
|
+
|
|
59
|
+
```yaml
|
|
60
|
+
search/weight-technology: "0.8"
|
|
61
|
+
search/weight-TechnologyService: "1.2"
|
|
62
|
+
```
|
|
63
|
+
|
|
50
64
|
## PDF settings
|
|
51
65
|
|
|
52
66
|
- **Colours** (`pdf/color-*`) are hex values (`#0b3d91`). `primary` is used for headings, the cover band and
|
|
@@ -167,6 +181,13 @@ class Archsight::Resources::Config < Archsight::Resources::Base
|
|
|
167
181
|
sidebar: false,
|
|
168
182
|
validator: ->(value) { Archsight::Summary::Lens.parse_error(value) }
|
|
169
183
|
|
|
184
|
+
annotation "search/weight-*",
|
|
185
|
+
description: "Weight of a layer (search/weight-technology) or of one kind (search/weight-Page) in the ranking " \
|
|
186
|
+
"of a text search: a number from 0 to 100, the relevance of a hit is multiplied by it",
|
|
187
|
+
title: "Search weight",
|
|
188
|
+
sidebar: false,
|
|
189
|
+
validator: ->(value) { Archsight::TextIndex::Weights.value_error(value) }
|
|
190
|
+
|
|
170
191
|
HEADER_PARTS = %w[id version date owner].freeze
|
|
171
192
|
HEADING_LEVELS = (1..6).to_a.freeze
|
|
172
193
|
KEEP_SPACE = /\A([1-6]):(\d{1,3})%?\z/
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# What a user writes as text search, turned into a safe FTS5 match expression. Words are ANDed; `OR`, `NOT`,
|
|
4
|
+
# parentheses, "phrases" and a trailing `*` (prefix) are FTS5 syntax and kept. Every other token is quoted, so
|
|
5
|
+
# `PROJ-1234` or `Archsight:CLI` search for those words next to each other instead of being FTS5 syntax.
|
|
6
|
+
module Archsight
|
|
7
|
+
class TextIndex
|
|
8
|
+
module Expression
|
|
9
|
+
TOKEN = /"((?:[^"]|"")*)"(\*)?|[()]|[^\s()"]+/
|
|
10
|
+
OPERATORS = %w[AND OR NOT].freeze
|
|
11
|
+
BAREWORD = /\A[\p{L}\p{N}_]+\z/
|
|
12
|
+
|
|
13
|
+
class << self
|
|
14
|
+
# @param prefix [Boolean] every plain word also matches as prefix (search box words while typing)
|
|
15
|
+
# @raise [Archsight::Query::QueryError] when nothing searchable is left
|
|
16
|
+
def translate(text, prefix: false)
|
|
17
|
+
found = tokens(text)
|
|
18
|
+
parts = found.map { |type, token, star| part(type, token, star || (prefix && type == :word)) }
|
|
19
|
+
searchable = found.any? { |type, _, _| %i[word phrase].include?(type) }
|
|
20
|
+
raise Archsight::Query::QueryError.new("Nothing to search for in #{text.inspect}", position: 0, source: nil) unless searchable
|
|
21
|
+
|
|
22
|
+
parts.join(" ")
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# The words and phrases that are searched for (not those after NOT), to show where they occur
|
|
26
|
+
def terms(text)
|
|
27
|
+
negated = false
|
|
28
|
+
tokens(text).each_with_object([]) do |(type, token, _), found|
|
|
29
|
+
if type == :operator
|
|
30
|
+
negated = token == "NOT"
|
|
31
|
+
elsif type != :paren
|
|
32
|
+
found << token unless negated
|
|
33
|
+
negated = false
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
private
|
|
39
|
+
|
|
40
|
+
# [[type, text, star]]: type :phrase, :word, :operator or :paren
|
|
41
|
+
def tokens(text)
|
|
42
|
+
text.to_s.to_enum(:scan, TOKEN).map do
|
|
43
|
+
match = Regexp.last_match
|
|
44
|
+
token = match[0]
|
|
45
|
+
if match[1]
|
|
46
|
+
[:phrase, match[1].gsub('""', '"'), !match[2].nil?]
|
|
47
|
+
elsif %w[( )].include?(token)
|
|
48
|
+
[:paren, token, false]
|
|
49
|
+
elsif OPERATORS.include?(token)
|
|
50
|
+
[:operator, token, false]
|
|
51
|
+
else
|
|
52
|
+
star = token.end_with?("*")
|
|
53
|
+
word = token.delete_suffix("*")
|
|
54
|
+
word.empty? ? nil : [:word, word, star]
|
|
55
|
+
end
|
|
56
|
+
end.compact
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
def part(type, token, star)
|
|
60
|
+
case type
|
|
61
|
+
when :paren, :operator then token
|
|
62
|
+
when :phrase then quote(token, star)
|
|
63
|
+
else token.match?(BAREWORD) ? "#{token}#{"*" if star}" : quote(token, star)
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def quote(text, star)
|
|
68
|
+
"\"#{text.gsub('"', '""')}\"#{"*" if star}"
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
end
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Archsight
|
|
4
|
+
class TextIndex
|
|
5
|
+
# Finds where the text conditions of a query occur in a text, to show hits in context. A full-text condition is
|
|
6
|
+
# looked for as the stems the index made of its words ("failovers" -> failov, matching failover, failovers, ...),
|
|
7
|
+
# at the start of a word and ignoring case and accents; a regex condition (`text =~ /x/`, `text(keys) =~ "x"`) as
|
|
8
|
+
# its regular expression, only in its keys.
|
|
9
|
+
class Matcher
|
|
10
|
+
# One thing to look for; `index` tells the patterns apart (a window with more different ones is better)
|
|
11
|
+
Pattern = Struct.new(:regexp, :key_patterns, :folded, :index) do
|
|
12
|
+
def applies_to?(key)
|
|
13
|
+
key_patterns.nil? || key_patterns.any? { |pattern| pattern.match?(key) }
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
WORD_CHAR = "[[:alnum:]]"
|
|
18
|
+
|
|
19
|
+
attr_reader :patterns
|
|
20
|
+
|
|
21
|
+
# The matcher of a parsed query (Archsight::Query::Query); empty when the query searches no text
|
|
22
|
+
def self.for(query, database)
|
|
23
|
+
conditions = text_conditions(query.ast)
|
|
24
|
+
return new([]) if conditions.empty?
|
|
25
|
+
|
|
26
|
+
index = TextIndex.for(database)
|
|
27
|
+
patterns = conditions.flat_map do |node|
|
|
28
|
+
fulltext = node.is_a?(Archsight::Query::AST::SearchTerms) || node.fulltext?
|
|
29
|
+
fulltext ? term_regexps(index, node.terms).map { |re| [re, nil, true] } : [[node.regexp, node.key_patterns, false]]
|
|
30
|
+
end
|
|
31
|
+
new(patterns.each_with_index.map { |(re, keys, folded), i| Pattern.new(re, keys, folded, i) })
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# The text conditions of a query that are not negated (sub-queries left out)
|
|
35
|
+
def self.text_conditions(node, found = [])
|
|
36
|
+
case node
|
|
37
|
+
when Archsight::Query::AST::QueryNode then text_conditions(node.expression, found)
|
|
38
|
+
when Archsight::Query::AST::BinaryOp
|
|
39
|
+
text_conditions(node.left, found)
|
|
40
|
+
text_conditions(node.right, found)
|
|
41
|
+
when Archsight::Query::AST::TextCondition, Archsight::Query::AST::SearchTerms then found << node
|
|
42
|
+
end
|
|
43
|
+
found
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# One regexp per word or phrase. Each word is found by its stem or as written (a prefix word such as `deploy`
|
|
47
|
+
# stems to `deploi`, which `deployed` does not start with), at the start of a word
|
|
48
|
+
def self.term_regexps(index, terms)
|
|
49
|
+
terms.filter_map do |term|
|
|
50
|
+
stems = index.stems(term)
|
|
51
|
+
next if stems.empty?
|
|
52
|
+
|
|
53
|
+
written = fold(term).downcase.scan(/[[:alnum:]]+/)
|
|
54
|
+
words = stems.each_with_index.map do |stem, i|
|
|
55
|
+
forms = [stem, (written[i] if written.size == stems.size)].compact.uniq
|
|
56
|
+
"(?:#{forms.map { |form| Regexp.escape(form) }.join("|")})"
|
|
57
|
+
end
|
|
58
|
+
Regexp.new("(?<!#{WORD_CHAR})#{words.join("#{WORD_CHAR}*[^[:alnum:]]+")}#{WORD_CHAR}*", Regexp::IGNORECASE)
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Accents taken off, character by character, so offsets stay those of the original text
|
|
63
|
+
def self.fold(text)
|
|
64
|
+
return text if text.ascii_only?
|
|
65
|
+
|
|
66
|
+
text.each_char.map { |char| char.ascii_only? ? char : (char.unicode_normalize(:nfd)[0] || char) }.join
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def initialize(patterns)
|
|
70
|
+
@patterns = patterns
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def empty?
|
|
74
|
+
@patterns.empty?
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# [[from, to, pattern index]] of every match in `text` of the annotation `key` (nil = a title), ordered
|
|
78
|
+
def ranges(text, key = nil)
|
|
79
|
+
folded = nil
|
|
80
|
+
@patterns.flat_map do |pattern|
|
|
81
|
+
next [] unless key.nil? ? pattern.key_patterns.nil? : pattern.applies_to?(key)
|
|
82
|
+
|
|
83
|
+
subject = pattern.folded ? (folded ||= self.class.fold(text)) : text
|
|
84
|
+
subject.to_enum(:scan, pattern.regexp).filter_map do
|
|
85
|
+
match = Regexp.last_match
|
|
86
|
+
[match.begin(0), match.end(0), pattern.index] if match.end(0) > match.begin(0)
|
|
87
|
+
end
|
|
88
|
+
end.sort
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
# [[from, to]] to mark in a title or name
|
|
92
|
+
def marks(text)
|
|
93
|
+
merge(ranges(text).map { |from, to, _| [from, to] })
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
def merge(marks)
|
|
97
|
+
marks.sort.each_with_object([]) do |(from, to), merged|
|
|
98
|
+
if merged.any? && from <= merged.last[1]
|
|
99
|
+
merged.last[1] = [merged.last[1], to].max
|
|
100
|
+
else
|
|
101
|
+
merged << [from, to]
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
end
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
end
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Archsight
|
|
4
|
+
class TextIndex
|
|
5
|
+
# Excerpts of a hit around the words its query searched for: the annotations where most of the searched words occur,
|
|
6
|
+
# each cut to the window that holds most of them, as plain text (markdown taken off) with the ranges to mark.
|
|
7
|
+
module Snippets
|
|
8
|
+
ELLIPSIS = "…"
|
|
9
|
+
# titles are shown as the title of a hit, not as an excerpt
|
|
10
|
+
TITLE_KEYS = %w[page/title architecture/title].freeze
|
|
11
|
+
|
|
12
|
+
class << self
|
|
13
|
+
# [{key:, title:, text:, marks: [[from, to]]}] of `instance`, best first, at most `limit`
|
|
14
|
+
def for(instance, matcher, limit: 2, width: 180)
|
|
15
|
+
return [] if matcher.empty?
|
|
16
|
+
|
|
17
|
+
candidates = instance.annotations.filter_map do |key, value|
|
|
18
|
+
next if !value.is_a?(String) || TITLE_KEYS.include?(key)
|
|
19
|
+
|
|
20
|
+
annotation = instance.class.annotation_matching(key)
|
|
21
|
+
text = annotation&.markdown? ? plain_markdown(value) : squeeze(value)
|
|
22
|
+
hits = matcher.ranges(text, key)
|
|
23
|
+
# a regex may look for the markdown itself (`text =~ /\[\[Page/`): then the excerpt is of the source
|
|
24
|
+
hits = matcher.ranges(text = squeeze(value), key) if hits.empty? && annotation&.markdown?
|
|
25
|
+
[key, annotation, text, hits] unless hits.empty?
|
|
26
|
+
end
|
|
27
|
+
best = candidates.sort_by { |key, _, _, hits| [-distinct(hits), -hits.size, key == "architecture/description" ? 0 : 1, key] }
|
|
28
|
+
best.first(limit).map do |key, annotation, text, hits|
|
|
29
|
+
title = annotation && !annotation.pattern? ? annotation.title : key
|
|
30
|
+
excerpt(text, hits, width, matcher).merge(key: key, title: title)
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# The title shown for a hit (page or architecture title, else the name) and what to mark in it
|
|
35
|
+
def title(instance, matcher)
|
|
36
|
+
text = instance.annotations["page/title"] || instance.annotations["architecture/title"] || instance.name.to_s
|
|
37
|
+
{ title: text, title_marks: matcher.empty? ? [] : matcher.marks(text) }
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Markdown as running text: no fences, headings, emphasis, link targets, tags or macros
|
|
41
|
+
def plain_markdown(text)
|
|
42
|
+
squeeze(
|
|
43
|
+
text.sub(/\A\s*#\s+[^\n]*\n/, "") # a leading title heading repeats the title of the hit
|
|
44
|
+
.gsub(/^\s*(```|~~~).*$/, " ")
|
|
45
|
+
.gsub(/^\s{0,3}\#{1,6}\s+/, "")
|
|
46
|
+
.gsub(/!\[([^\]]*)\]\([^)]*\)/, '\1')
|
|
47
|
+
.gsub(/\[([^\]]+)\]\([^)]*\)/, '\1')
|
|
48
|
+
.gsub(/\[\[(?:[^\]|]*\|)?([^\]]+)\]\]/, '\1')
|
|
49
|
+
.gsub(/<[^>]+>/, " ")
|
|
50
|
+
.gsub(/\{[a-z]+(?::[^}]*)?\}/, " ")
|
|
51
|
+
.gsub(/(\*\*|__|`)/, "")
|
|
52
|
+
.gsub(/^\s*[-*+>|]\s+/, "")
|
|
53
|
+
.tr("|", " ")
|
|
54
|
+
)
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def squeeze(text)
|
|
58
|
+
text.gsub(/\s+/, " ").strip
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
private
|
|
62
|
+
|
|
63
|
+
def distinct(hits)
|
|
64
|
+
hits.map(&:last).uniq.size
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# The window of about `width` characters with the most different searched words, at word boundaries
|
|
68
|
+
def excerpt(text, hits, width, matcher)
|
|
69
|
+
from, to = best_window(text, hits, width)
|
|
70
|
+
inside = hits.select { |start, stop, _| start >= from && stop <= to }
|
|
71
|
+
lead = from.positive? ? ELLIPSIS : ""
|
|
72
|
+
trail = to < text.length ? ELLIPSIS : ""
|
|
73
|
+
marks = matcher.merge(inside.map { |start, stop, _| [start - from + lead.length, stop - from + lead.length] })
|
|
74
|
+
{ text: "#{lead}#{text[from...to]}#{trail}", marks: marks }
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def best_window(text, hits, width)
|
|
78
|
+
return [0, text.length] if text.length <= width
|
|
79
|
+
|
|
80
|
+
windows = hits.map do |start, _, _|
|
|
81
|
+
from = (start - (width / 4)).clamp(0, text.length - width)
|
|
82
|
+
to = from + width
|
|
83
|
+
inside = hits.select { |s, e, _| s >= from && e <= to }
|
|
84
|
+
[from, to, distinct(inside), inside.size]
|
|
85
|
+
end
|
|
86
|
+
from, to, = windows.max_by { |f, _, kinds, count| [kinds, count, -f] }
|
|
87
|
+
[snap_start(text, from), snap_end(text, to)]
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# a window starts after a space (unless the text starts there) and ends before one
|
|
91
|
+
def snap_start(text, from)
|
|
92
|
+
return 0 if from.zero?
|
|
93
|
+
|
|
94
|
+
space = text.index(" ", from)
|
|
95
|
+
space && space - from < 20 ? space + 1 : from
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
def snap_end(text, to)
|
|
99
|
+
return text.length if to >= text.length
|
|
100
|
+
|
|
101
|
+
space = text.rindex(" ", to)
|
|
102
|
+
space && to - space < 20 ? space : to
|
|
103
|
+
end
|
|
104
|
+
end
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
end
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# How much a hit of a kind counts in the ranking of a text search: the relevance (bm25) is multiplied by it. Pages
|
|
4
|
+
# are what people look for first, then the application layer, technology last; settings kinds rank low. A Config of
|
|
5
|
+
# type `search` (the one named `default`, else the first) sets a layer with `search/weight-<layer>` and a single
|
|
6
|
+
# kind with `search/weight-<Kind>`. Order: configured kind, configured layer, built-in kind, built-in layer.
|
|
7
|
+
module Archsight
|
|
8
|
+
class TextIndex
|
|
9
|
+
class Weights
|
|
10
|
+
TYPE = "search" # the `config/type` of the Config that holds the weights
|
|
11
|
+
DEFAULT_CONFIG = "default"
|
|
12
|
+
PREFIX = "search/weight-"
|
|
13
|
+
MAX = 100
|
|
14
|
+
|
|
15
|
+
LAYER_DEFAULTS = {
|
|
16
|
+
"application" => 1.5,
|
|
17
|
+
"business" => 1.2,
|
|
18
|
+
"strategy" => 1.2,
|
|
19
|
+
"motivation" => 1.2,
|
|
20
|
+
"implementation" => 1.0,
|
|
21
|
+
"technology" => 1.0,
|
|
22
|
+
"other" => 0.5
|
|
23
|
+
}.freeze
|
|
24
|
+
|
|
25
|
+
KIND_DEFAULTS = {
|
|
26
|
+
"Page" => 3.0,
|
|
27
|
+
"ApplicationService" => 2.0,
|
|
28
|
+
"ApplicationComponent" => 2.0,
|
|
29
|
+
"ApplicationInterface" => 1.5
|
|
30
|
+
}.freeze
|
|
31
|
+
|
|
32
|
+
class << self
|
|
33
|
+
# The weights of the model (built-in defaults replaced by its search Config)
|
|
34
|
+
def for(database)
|
|
35
|
+
new(configured(database))
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# nil when the value is a valid weight, else the message (the validator of the Config annotation)
|
|
39
|
+
def value_error(value)
|
|
40
|
+
number = Float(value.to_s, exception: false)
|
|
41
|
+
number&.between?(0, MAX) ? nil : "expected a number from 0 to #{MAX} such as 1.5"
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
private
|
|
45
|
+
|
|
46
|
+
# {suffix => weight} of the search Config; values that are not valid weights are left out (the linter reports them)
|
|
47
|
+
def configured(database)
|
|
48
|
+
configs = database.instances_by_kind("Config").values.select { |c| c.annotations["config/type"].to_s.casecmp?(TYPE) }
|
|
49
|
+
config = configs.find { |c| c.name == DEFAULT_CONFIG } || configs.first
|
|
50
|
+
return {} unless config
|
|
51
|
+
|
|
52
|
+
config.annotations.each_with_object({}) do |(key, value), weights|
|
|
53
|
+
next unless key.start_with?(PREFIX) && value_error(value).nil?
|
|
54
|
+
|
|
55
|
+
weights[key.delete_prefix(PREFIX)] = Float(value.to_s)
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def initialize(configured = {})
|
|
61
|
+
@configured = configured
|
|
62
|
+
@cache = {}
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# The weight of a resource class
|
|
66
|
+
def [](klass)
|
|
67
|
+
@cache[klass] ||= begin
|
|
68
|
+
kind = klass.to_s.split("::").last
|
|
69
|
+
layer = klass.respond_to?(:layer) ? klass.layer : "other"
|
|
70
|
+
# as the summary lens: what the Config says beats the built-ins, the kind beats the layer
|
|
71
|
+
@configured[kind] || @configured[layer] || KIND_DEFAULTS[kind] || LAYER_DEFAULTS.fetch(layer, 1.0)
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
end
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "sqlite3"
|
|
4
|
+
require_relative "query/errors"
|
|
5
|
+
|
|
6
|
+
module Archsight
|
|
7
|
+
# Full-text index of the resources: an in-memory SQLite FTS5 table next to the model. It is contentless (only the
|
|
8
|
+
# index is kept, not a second copy of the text), one row per resource with two columns: `names` (name, aliases,
|
|
9
|
+
# titles) and `body` (every other string annotation). Queries answer resource => relevance (bm25, higher is better).
|
|
10
|
+
# Built by Database#text_index on first use and dropped on reload.
|
|
11
|
+
class TextIndex
|
|
12
|
+
# bm25 weights of the columns: a word in the name or title counts as much as ten in the body
|
|
13
|
+
COLUMN_WEIGHTS = [10.0, 1.0].freeze
|
|
14
|
+
NAME_KEYS = %w[architecture/aliases architecture/title page/title].freeze
|
|
15
|
+
TOKENIZER = "porter unicode61 remove_diacritics 2"
|
|
16
|
+
|
|
17
|
+
attr_reader :size
|
|
18
|
+
|
|
19
|
+
# The index of `database`: the one it keeps (Database#text_index), else a fresh one (test doubles)
|
|
20
|
+
def self.for(database)
|
|
21
|
+
database.respond_to?(:text_index) ? database.text_index : new(database)
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def initialize(database)
|
|
25
|
+
@resources = []
|
|
26
|
+
@mutex = Mutex.new
|
|
27
|
+
@db = SQLite3::Database.new(":memory:")
|
|
28
|
+
@db.execute("CREATE VIRTUAL TABLE fts USING fts5(names, body, content='', tokenize='#{TOKENIZER}')")
|
|
29
|
+
# a scratch table with the same tokenizer: what the index makes of a word (its stem), for highlighting
|
|
30
|
+
@db.execute("CREATE VIRTUAL TABLE stems USING fts5(text, tokenize='#{TOKENIZER}')")
|
|
31
|
+
@db.execute("CREATE VIRTUAL TABLE stems_vocab USING fts5vocab(stems, 'instance')")
|
|
32
|
+
build(database)
|
|
33
|
+
@size = @resources.size
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# Resource => score (higher is more relevant) for an FTS5 match expression (see Expression.translate)
|
|
37
|
+
# @raise [Archsight::Query::QueryError] if SQLite rejects the expression
|
|
38
|
+
def search(expression)
|
|
39
|
+
rows = @mutex.synchronize do
|
|
40
|
+
@db.execute("SELECT rowid, bm25(fts, #{COLUMN_WEIGHTS.join(", ")}) FROM fts WHERE fts MATCH ?", [expression])
|
|
41
|
+
end
|
|
42
|
+
rows.to_h { |rowid, score| [@resources[rowid - 1], -score] }
|
|
43
|
+
rescue SQLite3::SQLException => e
|
|
44
|
+
raise Archsight::Query::QueryError.new("Invalid text search #{expression.inspect}: #{e.message}", position: 0, source: nil)
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# The tokens the index makes of `text`, in order: lowercase, without accents, stemmed ("Failovers" -> "failov")
|
|
48
|
+
def stems(text)
|
|
49
|
+
@mutex.synchronize do
|
|
50
|
+
@db.execute("INSERT INTO stems(rowid, text) VALUES (1, ?)", [text.to_s])
|
|
51
|
+
tokens = @db.execute("SELECT term FROM stems_vocab WHERE doc = 1 ORDER BY offset").map(&:first)
|
|
52
|
+
@db.execute("DELETE FROM stems WHERE rowid = 1")
|
|
53
|
+
tokens
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
private
|
|
58
|
+
|
|
59
|
+
def build(database)
|
|
60
|
+
@db.transaction do
|
|
61
|
+
insert = @db.prepare("INSERT INTO fts(rowid, names, body) VALUES (?, ?, ?)")
|
|
62
|
+
database.instances.each_value do |by_name|
|
|
63
|
+
by_name.each_value do |instance|
|
|
64
|
+
@resources << instance
|
|
65
|
+
names, body = columns(instance)
|
|
66
|
+
insert.execute(@resources.size, names, body)
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
insert.close
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def columns(instance)
|
|
74
|
+
names = [instance.name.to_s]
|
|
75
|
+
body = []
|
|
76
|
+
instance.annotations.each do |key, value|
|
|
77
|
+
next unless value.is_a?(String)
|
|
78
|
+
|
|
79
|
+
(NAME_KEYS.include?(key) ? names : body) << value
|
|
80
|
+
end
|
|
81
|
+
[names.join("\n"), body.join("\n")]
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
require_relative "text_index/expression"
|
|
87
|
+
require_relative "text_index/weights"
|
|
88
|
+
require_relative "text_index/matcher"
|
|
89
|
+
require_relative "text_index/snippets"
|
data/lib/archsight/version.rb
CHANGED
|
@@ -146,21 +146,25 @@ module Archsight::Web::API::JsonHelpers
|
|
|
146
146
|
}
|
|
147
147
|
end
|
|
148
148
|
|
|
149
|
-
|
|
149
|
+
# `results` come in their order (ranked or by name); `scores` ({instance => relevance}) when ranked
|
|
150
|
+
def build_search_response(query, results, parsed_query, query_time_ms, scores: nil)
|
|
150
151
|
limit, offset = parse_pagination_params
|
|
151
152
|
output = parse_output_param
|
|
152
|
-
sorted = results.sort_by(&:name)
|
|
153
153
|
# `kind` narrows the hits to one kind; by_kind always counts all hits so the facets stay complete
|
|
154
154
|
kind = params[:kind].to_s
|
|
155
|
-
visible = kind.empty? ?
|
|
155
|
+
visible = kind.empty? ? results : results.select { |r| Archsight::MCP.kind_of(r) == kind }
|
|
156
156
|
pagination = paginate(visible, limit: limit, offset: offset)
|
|
157
|
+
context = search_context(parsed_query, scores)
|
|
157
158
|
|
|
158
159
|
instances = pagination[:items].map do |r|
|
|
159
|
-
resource_summary(r, output: output, omit_kind: false).merge(highlights: Archsight::MCP.highlights(r))
|
|
160
|
+
summary = resource_summary(r, output: output, omit_kind: false).merge(highlights: Archsight::MCP.highlights(r))
|
|
161
|
+
context ? summary.merge(context.call(r)) : summary
|
|
160
162
|
end
|
|
161
163
|
|
|
162
164
|
{
|
|
163
165
|
query: query,
|
|
166
|
+
sort: scores ? "relevance" : "name",
|
|
167
|
+
ranked: parsed_query.ranked?,
|
|
164
168
|
total: pagination[:total],
|
|
165
169
|
limit: pagination[:limit],
|
|
166
170
|
offset: pagination[:offset],
|
|
@@ -171,6 +175,21 @@ module Archsight::Web::API::JsonHelpers
|
|
|
171
175
|
}
|
|
172
176
|
end
|
|
173
177
|
|
|
178
|
+
# For a query that searches text: what each hit gets to show it in context (title with the searched words marked,
|
|
179
|
+
# excerpts of the annotations they occur in, relevance relative to the best hit); nil for other queries
|
|
180
|
+
def search_context(parsed_query, scores)
|
|
181
|
+
matcher = Archsight::TextIndex::Matcher.for(parsed_query, db)
|
|
182
|
+
return nil if matcher.empty?
|
|
183
|
+
|
|
184
|
+
top = scores&.values&.max.to_f
|
|
185
|
+
lambda do |resource|
|
|
186
|
+
context = Archsight::TextIndex::Snippets.title(resource, matcher)
|
|
187
|
+
context[:matches] = Archsight::TextIndex::Snippets.for(resource, matcher)
|
|
188
|
+
context[:relevance] = (scores[resource] / top).round(3) if scores && top.positive?
|
|
189
|
+
context
|
|
190
|
+
end
|
|
191
|
+
end
|
|
192
|
+
|
|
174
193
|
def extract_relations(instance)
|
|
175
194
|
relations = {}
|
|
176
195
|
|