wordmap 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/.github/workflows/rspec.yml +24 -0
- data/.gitignore +14 -0
- data/.rspec +3 -0
- data/CODE_OF_CONDUCT.md +74 -0
- data/Gemfile +4 -0
- data/LICENSE +201 -0
- data/README.md +169 -0
- data/Rakefile +6 -0
- data/bin/console +7 -0
- data/bin/setup +8 -0
- data/lib/wordmap.rb +101 -0
- data/lib/wordmap/access.rb +210 -0
- data/lib/wordmap/builder.rb +49 -0
- data/lib/wordmap/file_access.rb +75 -0
- data/lib/wordmap/index_value.rb +123 -0
- data/lib/wordmap/version.rb +3 -0
- data/wordmap.gemspec +28 -0
- metadata +122 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: f357e18c0e2199383ef82f3646e810a102841393b5f12f78455736d945205987
|
4
|
+
data.tar.gz: 18d38ade82bbaf981ffd5279f9f4edb8e9b6a38cbfe521aa45e3bf1f6c41d3ff
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 3f29ca3def2655f7acc36af95f7328620689c7cf7c366e015c196316e4027d1d283f1d36f0403abbc2367c986ae2683c4938dcdb7d25185135fa59fb9c72a3ed
|
7
|
+
data.tar.gz: 60ba8f842cea3d5d9269f4ab0eec323880f7827d4396ffacdc89d1154692d7ee72950ab745f30de79f09ab832894e05d13d6b1d16238d1438d1feac5659d2e09
|
@@ -0,0 +1,24 @@
|
|
1
|
+
name: RSpec
|
2
|
+
|
3
|
+
on:
|
4
|
+
push:
|
5
|
+
branches: [ main ]
|
6
|
+
pull_request:
|
7
|
+
branches: [ main ]
|
8
|
+
|
9
|
+
jobs:
|
10
|
+
test:
|
11
|
+
runs-on: ubuntu-latest
|
12
|
+
strategy:
|
13
|
+
matrix:
|
14
|
+
ruby: [ '2.4', '2.5', '2.6', '2.7' ]
|
15
|
+
|
16
|
+
name: Ruby ${{ matrix.ruby }}
|
17
|
+
steps:
|
18
|
+
- uses: actions/checkout@v2
|
19
|
+
- uses: actions/setup-ruby@v1
|
20
|
+
with:
|
21
|
+
ruby-version: ${{ matrix.ruby }}
|
22
|
+
- run: gem install bundler
|
23
|
+
- run: bundle install
|
24
|
+
- run: bundle exec rake
|
data/.gitignore
ADDED
data/.rspec
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,74 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
In the interest of fostering an open and welcoming environment, we as
|
6
|
+
contributors and maintainers pledge to making participation in our project and
|
7
|
+
our community a harassment-free experience for everyone, regardless of age, body
|
8
|
+
size, disability, ethnicity, gender identity and expression, level of experience,
|
9
|
+
nationality, personal appearance, race, religion, or sexual identity and
|
10
|
+
orientation.
|
11
|
+
|
12
|
+
## Our Standards
|
13
|
+
|
14
|
+
Examples of behavior that contributes to creating a positive environment
|
15
|
+
include:
|
16
|
+
|
17
|
+
* Using welcoming and inclusive language
|
18
|
+
* Being respectful of differing viewpoints and experiences
|
19
|
+
* Gracefully accepting constructive criticism
|
20
|
+
* Focusing on what is best for the community
|
21
|
+
* Showing empathy towards other community members
|
22
|
+
|
23
|
+
Examples of unacceptable behavior by participants include:
|
24
|
+
|
25
|
+
* The use of sexualized language or imagery and unwelcome sexual attention or
|
26
|
+
advances
|
27
|
+
* Trolling, insulting/derogatory comments, and personal or political attacks
|
28
|
+
* Public or private harassment
|
29
|
+
* Publishing others' private information, such as a physical or electronic
|
30
|
+
address, without explicit permission
|
31
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
32
|
+
professional setting
|
33
|
+
|
34
|
+
## Our Responsibilities
|
35
|
+
|
36
|
+
Project maintainers are responsible for clarifying the standards of acceptable
|
37
|
+
behavior and are expected to take appropriate and fair corrective action in
|
38
|
+
response to any instances of unacceptable behavior.
|
39
|
+
|
40
|
+
Project maintainers have the right and responsibility to remove, edit, or
|
41
|
+
reject comments, commits, code, wiki edits, issues, and other contributions
|
42
|
+
that are not aligned to this Code of Conduct, or to ban temporarily or
|
43
|
+
permanently any contributor for other behaviors that they deem inappropriate,
|
44
|
+
threatening, offensive, or harmful.
|
45
|
+
|
46
|
+
## Scope
|
47
|
+
|
48
|
+
This Code of Conduct applies both within project spaces and in public spaces
|
49
|
+
when an individual is representing the project or its community. Examples of
|
50
|
+
representing a project or community include using an official project e-mail
|
51
|
+
address, posting via an official social media account, or acting as an appointed
|
52
|
+
representative at an online or offline event. Representation of a project may be
|
53
|
+
further defined and clarified by project maintainers.
|
54
|
+
|
55
|
+
## Enforcement
|
56
|
+
|
57
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
58
|
+
reported by contacting the project team at max@bitsonnet.com. All
|
59
|
+
complaints will be reviewed and investigated and will result in a response that
|
60
|
+
is deemed necessary and appropriate to the circumstances. The project team is
|
61
|
+
obligated to maintain confidentiality with regard to the reporter of an incident.
|
62
|
+
Further details of specific enforcement policies may be posted separately.
|
63
|
+
|
64
|
+
Project maintainers who do not follow or enforce the Code of Conduct in good
|
65
|
+
faith may face temporary or permanent repercussions as determined by other
|
66
|
+
members of the project's leadership.
|
67
|
+
|
68
|
+
## Attribution
|
69
|
+
|
70
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
71
|
+
available at [https://contributor-covenant.org/version/1/4][version]
|
72
|
+
|
73
|
+
[homepage]: https://contributor-covenant.org
|
74
|
+
[version]: https://contributor-covenant.org/version/1/4/
|
data/Gemfile
ADDED
data/LICENSE
ADDED
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|
data/README.md
ADDED
@@ -0,0 +1,169 @@
|
|
1
|
+
![RSpec](https://github.com/scottscheapflights/wordmap/workflows/RSpec/badge.svg)
|
2
|
+
|
3
|
+
# Wordmap
|
4
|
+
|
5
|
+
A simple way to look up UTF-8 strings on disk by key(s) or index-powered queries without using any RAM.
|
6
|
+
|
7
|
+
Useful in cases where:
|
8
|
+
|
9
|
+
* RAM is more important than data access speed (1-3k reads/sec depending on SSD)
|
10
|
+
* Data is read-only (perhaps vendored with your repo)
|
11
|
+
* Your dataset might have many values, but they are not outrageously long or varied in size (the biggest value defines the "cell" size in the wordmap, and all others are padded to it)
|
12
|
+
|
13
|
+
## Installation
|
14
|
+
|
15
|
+
Add this line to your application's Gemfile:
|
16
|
+
|
17
|
+
```ruby
|
18
|
+
gem 'wordmap'
|
19
|
+
```
|
20
|
+
|
21
|
+
And then execute:
|
22
|
+
|
23
|
+
$ bundle install
|
24
|
+
|
25
|
+
Or install it yourself as:
|
26
|
+
|
27
|
+
$ gem install wordmap
|
28
|
+
|
29
|
+
## Usage
|
30
|
+
|
31
|
+
Before we can query a wordmap, we must create one first.
|
32
|
+
|
33
|
+
### Creating
|
34
|
+
|
35
|
+
Imagine you are storing fruit prices in cents, and fruits are also indexed by color and genus.
|
36
|
+
|
37
|
+
```ruby
|
38
|
+
entries = { 'banana' => '14', 'lemon' => '49' }
|
39
|
+
color = { 'banana' => 'yellow', 'lemon' => 'yellow' }
|
40
|
+
genus = { 'banana' => 'musa', 'lemon' => 'citrus' }
|
41
|
+
```
|
42
|
+
|
43
|
+
Now given the above 3 hashes, you can create a wordmap like this:
|
44
|
+
|
45
|
+
```ruby
|
46
|
+
Wordmap.create('path/to/fruits.wmap', entries, [:color, :genus]) do |index_name, key, value|
|
47
|
+
if index_name == :color
|
48
|
+
color[key]
|
49
|
+
else
|
50
|
+
genus[key]
|
51
|
+
end
|
52
|
+
end
|
53
|
+
```
|
54
|
+
|
55
|
+
In the above code snippet we specify the path where wordmap will be stored, the data itself (`entries`), and the optional 3rd argument, which lists any indexes we'd like to create. If a 3rd argument is given, then you must also supply a block. In this block you will get each `index_name`, `key`, and `value` combination from your entries, and your job is to return the corresponding index key for that combination.
|
56
|
+
|
57
|
+
### Querying
|
58
|
+
|
59
|
+
You can query a wordmap in 3 different ways.
|
60
|
+
|
61
|
+
#### 1. By key(s)
|
62
|
+
|
63
|
+
```ruby
|
64
|
+
fruits = Wordmap.new('path/to/fruits.wmap')
|
65
|
+
wordmap['banana'] # => ['14']
|
66
|
+
```
|
67
|
+
|
68
|
+
#### 2. By query
|
69
|
+
|
70
|
+
```ruby
|
71
|
+
fruits = Wordmap.new('path/to/fruits.wmap')
|
72
|
+
|
73
|
+
# Give me prices for banana and lemon.
|
74
|
+
fruits.query(%w[banana lemon]).to_a # => ["14", "49"]
|
75
|
+
|
76
|
+
# Give me prices for all yellow fruits.
|
77
|
+
fruits.query([:color, 'yellow']).to_a # => ["14", "49"]
|
78
|
+
|
79
|
+
# Give me prices for all yellow citruses.
|
80
|
+
fruits.query([:genus, 'citrus'], [:color, 'yellow']).to_a # => ["49"]
|
81
|
+
|
82
|
+
# Out of lemon and banana, give me prices for only citrus ones.
|
83
|
+
fruits.query(%w[lemon banana], [:genus, 'citrus']).to_a # => ["49"]
|
84
|
+
```
|
85
|
+
|
86
|
+
Each query is an array of arrays (outer array is omitted in the examples, because it works either way). Inner arrays are treated like unions (everything in them is `OR`'ed). Outer array is treated as an intersection (results of inner arrays are `AND`'ed with one another).
|
87
|
+
|
88
|
+
If an inner array starts with a symbol, the symbol is treated as an index name you want to look in.
|
89
|
+
|
90
|
+
Tip: if you are only supplying 1 array (as in the first and second examples above), you can drop all array wrappers entirely.
|
91
|
+
|
92
|
+
```ruby
|
93
|
+
fruits.query('banana', 'lemon')
|
94
|
+
fruits.query(:color, 'yellow')
|
95
|
+
```
|
96
|
+
|
97
|
+
**Result format**
|
98
|
+
|
99
|
+
The result is always a lazy enumerable of UTF-8 strings, which is why you see me call `.to_a` on each of them. Wordmap is trying to read files as lazily as possible.
|
100
|
+
|
101
|
+
**Results order**
|
102
|
+
|
103
|
+
The result values are in the order of how data is arranged in the wordmap's data file, which itself is based on lexicographical sorting of keys.
|
104
|
+
|
105
|
+
#### 3. Sequentially
|
106
|
+
|
107
|
+
If you just want to read all values sequentially, you can treat a wordmap as an [Enumerable](https://ruby-doc.org/core/Enumerable.html).
|
108
|
+
|
109
|
+
```ruby
|
110
|
+
fruits.select { |price| price.to_i < 40 } # => ["14"]
|
111
|
+
```
|
112
|
+
|
113
|
+
You have access to `.each` method, but it also accepts an argument. If you pass an integer, you can iterate over a single vector (a key dimension, see [Multi-dimensional keys](#multi-dimensional-keys) ). Since fruits is 1-dimensional array, you can only iterate over 0th dimension.
|
114
|
+
|
115
|
+
```ruby
|
116
|
+
fruits.each.to_a # => ["14", "49"]
|
117
|
+
fruits.each(0).to_a # => ["banana", "lemon"]
|
118
|
+
```
|
119
|
+
|
120
|
+
You can pass a symbol to iterate sequentially over index keys.
|
121
|
+
|
122
|
+
```ruby
|
123
|
+
fruits.each(:genus).to_a # => ["citrus", "musa"]
|
124
|
+
```
|
125
|
+
|
126
|
+
### Multi-dimensional keys
|
127
|
+
|
128
|
+
In the above examples the keys are simply `'banana'` and `'lemon'` — strings. If you make your key an array of strings, that'd make a multi-dimensional key. This can come helpful for some data where 2 keys make sense (we have such use cases at Scott's). Internally, each dimension is a different vector. However if you go that route, keep in mind that all the "unused" key combinations will create gaps in the data file, therefore inflating its size. For example, if you make a key out of genus + name of a fruit, like `%w[citrus lemon]` and `%w[musa banana]`, your file will become inflated with empty cells created for `%w[citrus banana]`, `%w[musa lemon]`. That space is taken (padded with null bytes) even if there are no values for these keys.
|
129
|
+
|
130
|
+
## Anatomy
|
131
|
+
|
132
|
+
A wordmap on disk is just a directory with a few files in it.
|
133
|
+
|
134
|
+
### `data` file
|
135
|
+
|
136
|
+
The data file is where the actual entries are stored. When a wordmap is created, it looks through all the entries you want to store, and finds one with the maximum bytesize. Then it makes all entries that size by padding them with null bytes in front, and dumping all of them into the file. Since this makes each entry in the file the same size, we can easily seek to any single entry by knowing its index, because it's just index times entry size. We call such padded entry a "cell".
|
137
|
+
|
138
|
+
The important part is the order of data in this file. When a wordmap is created, all the keys are sorted lexicographically, and for every key, entry is written in the order of how the corresponding keys are sorted. This means that if we know index of where a key is positioned sequentially, we also know index of where the cell is in the data file.
|
139
|
+
|
140
|
+
### `vec` files
|
141
|
+
|
142
|
+
Vector files are where keys are stored. If you used a string as a lookup key, then it creates just one vector file where every key is written in a cell padded to maximum key length just like the case with the data file. Since this file is sorted, we can easily binary-search a key in this file, and then seek to corresponding position in the data file to find the entry.
|
143
|
+
|
144
|
+
For multi-dimensional keys, multiple vector files are created (one per dimension). Let's say we have 2-dimensional key (a key that's an array of 2 strings). The first vector will contain all the first strings, and second all the second strings. Now when wordmap is doing a lookup by key, it will first bsearch the first vector to find a "page" of entries in the data file, then it will bsearch the second vector to find an exact entry position in that page of entries. Then it will know exactly where to seek to grab the entry from the data file.
|
145
|
+
|
146
|
+
### Metadata
|
147
|
+
|
148
|
+
Data and vector files each have a couple of numbers at the beginning that specify cells' bytesize and count. This is the only part that wordmap reads into RAM when instantiated: 2 integers per file. Having read metadata we can derive 2 additional pieces of information: 1. the bytesize of the metadata itself, so that we can skip over it, and 2. how many cells we should read every time we read a lot of cells (to optimize sequential reads). The latter is always trying to be near ~10kb per read (unless a single cell is longer than 10kb, then it's using single cell's size).
|
149
|
+
|
150
|
+
### Indexes
|
151
|
+
|
152
|
+
Indexes are just wordmaps nested inside the wordmap you create. These inner wordmaps have index keys as the keys, and lists of locations as values. The values of indexes are invisible to the end user, but since this section is about anatomy, it makes sense to mention them. The locations are stored as a comma-separated list of [delta encoded](https://en.wikipedia.org/wiki/Delta_encoding) sorted integers and ranges. For example, if we are storing locations `1,3,5,6,7,8,12,15` the stored value will look like this: `1,2,2+3,4,3`. You can unpack this value by saying "first position is **1**, second position is 1 + 2 = **3**, third position is 3 + 2 = **5**, now add 3 more successively: **6,7,8**, then 8 + 4 = **12**, and 12 + 3 = **15**".
|
153
|
+
|
154
|
+
When processing a query, wordmap produces lazy iterators for unioning and intersecting data. These iterators lazily walk indexed locations, or keys in a vector file, and return each found entry from the data file.
|
155
|
+
|
156
|
+
## Development
|
157
|
+
|
158
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
159
|
+
|
160
|
+
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 tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
161
|
+
|
162
|
+
## Contributing
|
163
|
+
|
164
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/wordmap. 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]/wordmap/blob/master/CODE_OF_CONDUCT.md).
|
165
|
+
|
166
|
+
|
167
|
+
## Code of Conduct
|
168
|
+
|
169
|
+
Everyone interacting in the Wordmap project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/wordmap/blob/master/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
data/bin/console
ADDED
data/bin/setup
ADDED
data/lib/wordmap.rb
ADDED
@@ -0,0 +1,101 @@
|
|
1
|
+
require 'wordmap/version'
|
2
|
+
require 'wordmap/builder'
|
3
|
+
require 'wordmap/access'
|
4
|
+
require 'tmpdir'
|
5
|
+
require 'fileutils'
|
6
|
+
|
7
|
+
class Wordmap
|
8
|
+
include Enumerable
|
9
|
+
|
10
|
+
attr_reader :size
|
11
|
+
|
12
|
+
SPACER = "\0".freeze
|
13
|
+
LTRIM_REGEX = /\A#{SPACER}+/.freeze
|
14
|
+
|
15
|
+
class << self
|
16
|
+
def create(path, hash, index_names = [])
|
17
|
+
raise ArgumentError, "Path already exists: #{path}" if Dir.exists?(path)
|
18
|
+
|
19
|
+
index_data = index_names.map { |name| [name, {}] }.to_h
|
20
|
+
vecs = Builder.build_vectors(hash)
|
21
|
+
cells_c = vecs.map(&:size).reduce(:*)
|
22
|
+
|
23
|
+
Dir.mktmpdir do |dirpath|
|
24
|
+
vecs.each.with_index do |vec, i|
|
25
|
+
Builder.write_vector("#{dirpath}/vec#{i}", vec, SPACER)
|
26
|
+
end
|
27
|
+
|
28
|
+
Builder.write_data(dirpath, vecs, cells_c, hash, SPACER) do |k, v, i|
|
29
|
+
index_names.each do |name|
|
30
|
+
index_keys = Array(yield(name, k, v)).compact
|
31
|
+
next if index_keys.empty?
|
32
|
+
index_keys.each do |index_key|
|
33
|
+
index_data[name][index_key] ||= []
|
34
|
+
index_data[name][index_key] << i
|
35
|
+
end
|
36
|
+
end
|
37
|
+
end
|
38
|
+
|
39
|
+
index_data.each do |name, data|
|
40
|
+
next if data.empty?
|
41
|
+
data.transform_values! { |v| IndexValue.pack(v) }
|
42
|
+
create("#{dirpath}/i-#{name}.wmap", data)
|
43
|
+
end
|
44
|
+
|
45
|
+
FileUtils.cp_r(dirpath, path)
|
46
|
+
end
|
47
|
+
end
|
48
|
+
end
|
49
|
+
|
50
|
+
def initialize(path)
|
51
|
+
@descriptors = Access.load_descriptors(Dir["#{path}/{vec*,data}"], SPACER)
|
52
|
+
@indexes = load_indexes(Dir["#{path}/i-*"])
|
53
|
+
@size = @descriptors['data'][:meta][:cell_count]
|
54
|
+
end
|
55
|
+
|
56
|
+
# Query consists of one or more clauses. Each clause is an array.
|
57
|
+
#
|
58
|
+
# Clauses can have 2 shapes:
|
59
|
+
#
|
60
|
+
# 1. ['key1', 'key2', ...] # match any of these main keys
|
61
|
+
# 2. [:index_name, 'key1', 'key2', ...] # match by any of these index keys
|
62
|
+
#
|
63
|
+
# - OR logic is used inside a clause (matches are unioned)
|
64
|
+
# - AND logic is used between clauses (matches are intersected)
|
65
|
+
#
|
66
|
+
# Example 1:
|
67
|
+
#
|
68
|
+
# query(['horse1', 'horse2', 'horse3'], [:trait, 'fluffy'])
|
69
|
+
#
|
70
|
+
# Out of horse1, horse2, horse3 return only the fluffy ones.
|
71
|
+
#
|
72
|
+
# Example 2:
|
73
|
+
#
|
74
|
+
# query([:color, 'orange', 'green'], [:type, 'vegetable', 'fruit'])
|
75
|
+
#
|
76
|
+
# Return all orange and green fruits and vegetables.
|
77
|
+
def query(*query, trace: nil)
|
78
|
+
enum =
|
79
|
+
Access.each_by_query(@descriptors, @indexes, query, LTRIM_REGEX, trace)
|
80
|
+
block_given? ? enum.each { |v| yield(v) } : enum
|
81
|
+
end
|
82
|
+
|
83
|
+
def [](*key, trace: nil)
|
84
|
+
Access.each_by_key(@descriptors, key, LTRIM_REGEX, trace).to_a
|
85
|
+
end
|
86
|
+
|
87
|
+
def each(vec_or_index = nil, trace: nil)
|
88
|
+
enum = Access.each(@descriptors, @indexes, vec_or_index, LTRIM_REGEX, trace)
|
89
|
+
block_given? ? enum.each { |v| yield(v) } : enum
|
90
|
+
end
|
91
|
+
|
92
|
+
private
|
93
|
+
|
94
|
+
def load_indexes(paths)
|
95
|
+
paths.reduce({}) { |hash, path|
|
96
|
+
name = File.basename(path, '.wmap')[2..-1].to_sym
|
97
|
+
hash.merge(name => self.class.new(path))
|
98
|
+
}
|
99
|
+
end
|
100
|
+
end
|
101
|
+
|
@@ -0,0 +1,210 @@
|
|
1
|
+
require 'wordmap/file_access'
|
2
|
+
require 'wordmap/index_value'
|
3
|
+
|
4
|
+
class Wordmap
|
5
|
+
module Access
|
6
|
+
module_function
|
7
|
+
|
8
|
+
def load_descriptors(paths, spacer)
|
9
|
+
paths.reduce({}) { |hash, path|
|
10
|
+
file = File.open(path, 'rb')
|
11
|
+
meta = FileAccess.read_meta(file, spacer)
|
12
|
+
hash.merge(File.basename(path) => { file: file, meta: meta })
|
13
|
+
}
|
14
|
+
end
|
15
|
+
|
16
|
+
def each_by_query descriptors, indexes, query, ltrim_regex, trace
|
17
|
+
unless block_given?
|
18
|
+
return enum_for(
|
19
|
+
__method__, descriptors, indexes, query, ltrim_regex, trace
|
20
|
+
)
|
21
|
+
end
|
22
|
+
|
23
|
+
index_values =
|
24
|
+
if query.none? { |clause| clause.is_a?(Array) }
|
25
|
+
[
|
26
|
+
clause_to_index_value(
|
27
|
+
query, descriptors, indexes, ltrim_regex, trace
|
28
|
+
)
|
29
|
+
]
|
30
|
+
else
|
31
|
+
# Proactively intersect all clauses of the same type to save on reads.
|
32
|
+
map_normalized_clauses(query) { |clause|
|
33
|
+
clause_to_index_value \
|
34
|
+
clause, descriptors, indexes, ltrim_regex, trace
|
35
|
+
}
|
36
|
+
end
|
37
|
+
|
38
|
+
IndexValue
|
39
|
+
.each_seq_value(*index_values)
|
40
|
+
.lazy
|
41
|
+
.slice_when { |a, b| b > a.succ }
|
42
|
+
.each { |seq|
|
43
|
+
subtrace = nil
|
44
|
+
if trace
|
45
|
+
subtrace = []
|
46
|
+
trace << [:each_by_query, "#{seq.first}-#{seq.last}", subtrace]
|
47
|
+
end
|
48
|
+
|
49
|
+
FileAccess
|
50
|
+
.each_cell(descriptors['data'][:file], seq[0],
|
51
|
+
count: seq.size,
|
52
|
+
meta: descriptors['data'][:meta],
|
53
|
+
trace: subtrace
|
54
|
+
) { |cell|
|
55
|
+
value = extract_value(cell, ltrim_regex)
|
56
|
+
yield(value) unless value.empty?
|
57
|
+
}
|
58
|
+
}
|
59
|
+
end
|
60
|
+
|
61
|
+
def each_by_key(descriptors, key, ltrim_regex, trace)
|
62
|
+
unless block_given?
|
63
|
+
return enum_for(__method__, descriptors, key, ltrim_regex, trace)
|
64
|
+
end
|
65
|
+
|
66
|
+
index_value = index_value_by_key(descriptors, key, ltrim_regex, trace)
|
67
|
+
return [].to_enum if index_value == ''
|
68
|
+
seq = IndexValue.each_seq_value(index_value).to_a
|
69
|
+
|
70
|
+
subtrace = nil
|
71
|
+
|
72
|
+
if trace
|
73
|
+
subtrace = []
|
74
|
+
trace << [:each_by_key, "#{seq.first}-#{seq.last}", subtrace]
|
75
|
+
end
|
76
|
+
|
77
|
+
FileAccess.each_cell(descriptors['data'][:file], seq[0],
|
78
|
+
count: seq.size,
|
79
|
+
meta: descriptors['data'][:meta],
|
80
|
+
trace: subtrace
|
81
|
+
) { |cell|
|
82
|
+
value = extract_value(cell, ltrim_regex)
|
83
|
+
yield(value) unless value.empty?
|
84
|
+
}
|
85
|
+
end
|
86
|
+
|
87
|
+
def each(descriptors, indexes, vec_or_index, ltrim_regex, trace)
|
88
|
+
unless block_given?
|
89
|
+
return enum_for(
|
90
|
+
__method__,
|
91
|
+
descriptors,
|
92
|
+
indexes,
|
93
|
+
vec_or_index,
|
94
|
+
ltrim_regex,
|
95
|
+
trace
|
96
|
+
)
|
97
|
+
end
|
98
|
+
|
99
|
+
case vec_or_index
|
100
|
+
when NilClass, Integer
|
101
|
+
descriptor = vec_or_index.nil? ? 'data' : "vec#{vec_or_index}"
|
102
|
+
file, meta = descriptors[descriptor].values_at(:file, :meta)
|
103
|
+
|
104
|
+
subtrace = nil
|
105
|
+
|
106
|
+
if trace
|
107
|
+
subtrace = []
|
108
|
+
trace << [:each, descriptor, subtrace]
|
109
|
+
end
|
110
|
+
|
111
|
+
FileAccess.each_cell(file, meta: meta, trace: subtrace) { |cell|
|
112
|
+
value = extract_value(cell, ltrim_regex)
|
113
|
+
yield(value) unless value.empty?
|
114
|
+
}
|
115
|
+
when Symbol
|
116
|
+
raise "Unknown index: #{vec_or_index}" unless indexes.key?(vec_or_index)
|
117
|
+
|
118
|
+
subtrace = nil
|
119
|
+
|
120
|
+
if trace
|
121
|
+
subtrace = []
|
122
|
+
trace << [:each, vec_or_index, subtrace]
|
123
|
+
end
|
124
|
+
|
125
|
+
indexes[vec_or_index].each(0, trace: subtrace) { |cell| yield(cell) }
|
126
|
+
subtrace.replace(subtrace.flat_map { |v| v[2] }) if trace
|
127
|
+
else
|
128
|
+
raise 'Invalid value passed into each'
|
129
|
+
end
|
130
|
+
end
|
131
|
+
|
132
|
+
def index_value_by_key(descriptors, key, ltrim_regex, trace)
|
133
|
+
key = Array(key)
|
134
|
+
cell_count = descriptors['data'][:meta][:cell_count]
|
135
|
+
|
136
|
+
cell_c, cell_i =
|
137
|
+
0.upto(key.size - 1).reduce([cell_count, 0]) { |(cc, ci), vi|
|
138
|
+
vec_desc = descriptors["vec#{vi}"]
|
139
|
+
return '' unless vec_desc
|
140
|
+
vmeta = vec_desc[:meta]
|
141
|
+
vfile = vec_desc[:file]
|
142
|
+
vec_index = bsearch_vec(vfile, key[vi], vmeta, ltrim_regex, trace)
|
143
|
+
return '' unless vec_index
|
144
|
+
page_size = cc / vmeta[:cell_count]
|
145
|
+
[page_size, ci + (page_size * vec_index)]
|
146
|
+
}
|
147
|
+
|
148
|
+
cell_c > 1 ? "#{cell_i}+#{cell_c - 1}" : "#{cell_i}"
|
149
|
+
end
|
150
|
+
|
151
|
+
def bsearch_vec(file, value, meta, ltrim_regex, trace)
|
152
|
+
subtrace = nil
|
153
|
+
|
154
|
+
if trace
|
155
|
+
subtrace = []
|
156
|
+
trace << [__method__, value, subtrace]
|
157
|
+
end
|
158
|
+
|
159
|
+
(0..(meta[:cell_count] - 1)).bsearch { |i|
|
160
|
+
cell = FileAccess.read_cells(file, i, 1, meta, subtrace)[0]
|
161
|
+
value <=> extract_value(cell, ltrim_regex)
|
162
|
+
}
|
163
|
+
end
|
164
|
+
|
165
|
+
def clause_to_index_value(clause, descriptors, indexes, ltrim_regex, trace)
|
166
|
+
name, *keys = clause
|
167
|
+
|
168
|
+
case name
|
169
|
+
when Symbol
|
170
|
+
raise "Unknown index: #{name}" unless indexes.key?(name)
|
171
|
+
keys.map { |key| indexes[name][key, trace: trace].first || '' }
|
172
|
+
else
|
173
|
+
# For vector lookup, if keys are sorted, then positions are guaranteed
|
174
|
+
# to be sorted too, which means we can get away with getting locations
|
175
|
+
# lazily here.
|
176
|
+
vec_iterator(descriptors, Array(clause), ltrim_regex, trace)
|
177
|
+
end
|
178
|
+
end
|
179
|
+
|
180
|
+
def vec_iterator(descriptors, keys, ltrim_regex, trace = nil)
|
181
|
+
unless block_given?
|
182
|
+
return enum_for(__method__, descriptors, keys, ltrim_regex, trace)
|
183
|
+
end
|
184
|
+
|
185
|
+
keys.sort.each do |key|
|
186
|
+
value = index_value_by_key(descriptors, key, ltrim_regex, trace)
|
187
|
+
next if value.nil? || value == ''
|
188
|
+
yield(value.to_i)
|
189
|
+
end
|
190
|
+
end
|
191
|
+
|
192
|
+
def map_normalized_clauses(query)
|
193
|
+
query
|
194
|
+
.reduce({}) { |normalized, clause|
|
195
|
+
normalized.merge(
|
196
|
+
clause[0].is_a?(Symbol) ?
|
197
|
+
{ clause[0] => clause[1..-1] } :
|
198
|
+
{ '_keys' => clause }
|
199
|
+
) { |_, oldv, newv| oldv & newv }
|
200
|
+
}
|
201
|
+
.map { |name, keys|
|
202
|
+
name == '_keys' ? yield(keys) : yield([name, *keys])
|
203
|
+
}
|
204
|
+
end
|
205
|
+
|
206
|
+
def extract_value(cell, regex)
|
207
|
+
cell.sub(regex, '').force_encoding('utf-8')
|
208
|
+
end
|
209
|
+
end
|
210
|
+
end
|
@@ -0,0 +1,49 @@
|
|
1
|
+
require 'wordmap/index_value'
|
2
|
+
|
3
|
+
class Wordmap
|
4
|
+
module Builder
|
5
|
+
module_function
|
6
|
+
|
7
|
+
def build_vectors(hash)
|
8
|
+
vectors = hash.first[0].is_a?(Array) ? hash.keys.transpose : [hash.keys]
|
9
|
+
vectors.map!(&:uniq)
|
10
|
+
vectors.map!(&:sort)
|
11
|
+
vectors
|
12
|
+
end
|
13
|
+
|
14
|
+
# TODO: drop null bytes at the beginning (offset in meta)
|
15
|
+
# TODO: drop null bytes at the end
|
16
|
+
def write_data(path, vecs, cells_c, hash, spacer)
|
17
|
+
File.open("#{path}/data", 'wb') do |file|
|
18
|
+
cell_w = hash.values.max_by(&:bytesize).bytesize
|
19
|
+
file.write("#{cell_w},#{cells_c}#{spacer}")
|
20
|
+
|
21
|
+
key_iterator =
|
22
|
+
vecs.size == 1 ? vecs[0].each : vecs[0].product(*vecs[1..-1]).to_enum
|
23
|
+
|
24
|
+
key_iterator.with_index do |key, cell_i|
|
25
|
+
value = hash[key].to_s
|
26
|
+
yield(key, value, cell_i) unless value.empty?
|
27
|
+
file.write(rjust_bytes(value, cell_w, spacer))
|
28
|
+
end
|
29
|
+
end
|
30
|
+
end
|
31
|
+
|
32
|
+
def write_vector(path, vector, spacer)
|
33
|
+
cell_w = vector.max_by(&:bytesize).bytesize
|
34
|
+
|
35
|
+
File.open(path, 'wb') do |file|
|
36
|
+
file.write("#{cell_w},#{vector.size}#{spacer}")
|
37
|
+
|
38
|
+
vector.each do |key|
|
39
|
+
file.write(rjust_bytes(key.to_s, cell_w, spacer))
|
40
|
+
end
|
41
|
+
end
|
42
|
+
end
|
43
|
+
|
44
|
+
def rjust_bytes(string, bytesize, spacer)
|
45
|
+
difference = bytesize - string.bytesize
|
46
|
+
(spacer * difference) + string
|
47
|
+
end
|
48
|
+
end
|
49
|
+
end
|
@@ -0,0 +1,75 @@
|
|
1
|
+
class Wordmap
|
2
|
+
module FileAccess
|
3
|
+
module_function
|
4
|
+
|
5
|
+
def each_cell file, start = 0,
|
6
|
+
meta:,
|
7
|
+
count: Float::INFINITY,
|
8
|
+
batch_size: meta[:batch_size],
|
9
|
+
trace: nil
|
10
|
+
|
11
|
+
unless block_given?
|
12
|
+
return enum_for(__method__, file, start,
|
13
|
+
meta: meta,
|
14
|
+
count: count,
|
15
|
+
batch_size: batch_size,
|
16
|
+
trace: trace
|
17
|
+
)
|
18
|
+
end
|
19
|
+
|
20
|
+
seen = 0
|
21
|
+
|
22
|
+
loop do
|
23
|
+
batch_size = count if (count < batch_size)
|
24
|
+
cells = read_cells(file, start + seen, batch_size, meta, trace)
|
25
|
+
cells.each do |cell|
|
26
|
+
yield(cell)
|
27
|
+
end
|
28
|
+
|
29
|
+
seen += cells.size
|
30
|
+
count -= cells.size
|
31
|
+
break if count < 1
|
32
|
+
break if cells.size < batch_size
|
33
|
+
end
|
34
|
+
end
|
35
|
+
|
36
|
+
def read_cells(file, i, count, meta, trace)
|
37
|
+
meta_offset, cell_size, cell_count =
|
38
|
+
meta.values_at(:offset, :cell_size, :cell_count)
|
39
|
+
|
40
|
+
return [] if i + 1 > meta[:cell_count]
|
41
|
+
|
42
|
+
if i + count + 1 > meta[:cell_count]
|
43
|
+
count = (meta[:cell_count] - i)
|
44
|
+
end
|
45
|
+
|
46
|
+
pos = meta[:offset] + (i * meta[:cell_size])
|
47
|
+
bytes = meta[:cell_size] * count
|
48
|
+
|
49
|
+
if trace
|
50
|
+
parts = file.path.split('.wmap', 2)
|
51
|
+
subpath = (File.basename(parts[0]) + '.wmap') + parts[1]
|
52
|
+
trace << [:read_cells, subpath, i, count, pos, bytes]
|
53
|
+
end
|
54
|
+
read_at(file, pos, bytes).unpack("a#{meta[:cell_size]}" * count)
|
55
|
+
end
|
56
|
+
|
57
|
+
def read_meta(file, spacer)
|
58
|
+
meta_string = read_at(file, 0, 30).split(spacer, 2)[0]
|
59
|
+
cell_size, cell_count = meta_string.split(',').map(&:to_i)
|
60
|
+
{
|
61
|
+
offset: meta_string.bytesize + 1,
|
62
|
+
cell_size: cell_size,
|
63
|
+
cell_count: cell_count,
|
64
|
+
batch_size: [[10_000 / cell_size, 1].max, cell_count].min
|
65
|
+
}
|
66
|
+
end
|
67
|
+
|
68
|
+
def read_at(file, pos, bytes)
|
69
|
+
# puts "Seeking in #{file.path.split('.wmap', 2)[1][1..-1]} to #{pos}, " \
|
70
|
+
# "and reading #{bytes} bytes"
|
71
|
+
file.sysseek(pos)
|
72
|
+
file.sysread(bytes)
|
73
|
+
end
|
74
|
+
end
|
75
|
+
end
|
@@ -0,0 +1,123 @@
|
|
1
|
+
require 'set'
|
2
|
+
|
3
|
+
class Wordmap
|
4
|
+
module IndexValue
|
5
|
+
module_function
|
6
|
+
|
7
|
+
def pack(numbers)
|
8
|
+
last = 0
|
9
|
+
|
10
|
+
numbers
|
11
|
+
.slice_when { |a, b| b > a.succ }
|
12
|
+
.map { |h, *t| [h - last, t.size].tap { last = t.last || h } }
|
13
|
+
.map { |v, r| r.zero? ? v.to_s : "#{v}+#{r}" }
|
14
|
+
.join(',')
|
15
|
+
end
|
16
|
+
|
17
|
+
def each_seq_value(*arrays_of_seqs)
|
18
|
+
return enum_for(__method__, *arrays_of_seqs) unless block_given?
|
19
|
+
|
20
|
+
iters = arrays_of_seqs.map { |union_array|
|
21
|
+
case union_array
|
22
|
+
when Enumerator; [union_array]
|
23
|
+
when String; [iterator(union_array)]
|
24
|
+
else; union_array.map { |seq| iterator(seq) }
|
25
|
+
end
|
26
|
+
}
|
27
|
+
|
28
|
+
combine(*iters) { |value| yield(value) }
|
29
|
+
end
|
30
|
+
|
31
|
+
def combine(*arrays_of_iters)
|
32
|
+
return enum_for(__method__, *arrays_of_iters) unless block_given?
|
33
|
+
intersect(*arrays_of_iters.map { |array| uniq_union(*array) }) do |value|
|
34
|
+
yield(value)
|
35
|
+
end
|
36
|
+
end
|
37
|
+
|
38
|
+
def intersect(*iters)
|
39
|
+
return enum_for(__method__, *iters) unless block_given?
|
40
|
+
|
41
|
+
last = nil
|
42
|
+
given = 0
|
43
|
+
wrap_up = false
|
44
|
+
|
45
|
+
union(*iters, control_messages: true) do |value|
|
46
|
+
if value == :__iter_exhausted
|
47
|
+
wrap_up = true
|
48
|
+
next
|
49
|
+
end
|
50
|
+
|
51
|
+
break if wrap_up && last != value
|
52
|
+
|
53
|
+
last == value ? (given += 1) : (given = 1)
|
54
|
+
yield(value) if given == iters.size
|
55
|
+
last = value
|
56
|
+
end
|
57
|
+
end
|
58
|
+
|
59
|
+
def uniq_union(*iters)
|
60
|
+
return enum_for(__method__, *iters) unless block_given?
|
61
|
+
|
62
|
+
last = nil
|
63
|
+
|
64
|
+
union(*iters) do |value|
|
65
|
+
yield(value) unless value == last
|
66
|
+
last = value
|
67
|
+
end
|
68
|
+
end
|
69
|
+
|
70
|
+
def union(*iters, control_messages: false)
|
71
|
+
unless block_given?
|
72
|
+
return enum_for(__method__, *iters, control_messages: control_messages)
|
73
|
+
end
|
74
|
+
|
75
|
+
iters = iters.map { |iter| [iter.rewind, true] }
|
76
|
+
|
77
|
+
loop do
|
78
|
+
iter_exhausted = false
|
79
|
+
|
80
|
+
next_iter =
|
81
|
+
iters.select { |iter| iter[1] }.min_by do |iter|
|
82
|
+
begin
|
83
|
+
iter[0].peek
|
84
|
+
rescue StopIteration
|
85
|
+
iter[1] = false
|
86
|
+
iter_exhausted = true
|
87
|
+
next(Float::INFINITY)
|
88
|
+
end
|
89
|
+
end
|
90
|
+
|
91
|
+
all_iters_exhausted = iters.none? { |iter| iter[1] }
|
92
|
+
|
93
|
+
if control_messages && iter_exhausted && !all_iters_exhausted
|
94
|
+
yield(:__iter_exhausted)
|
95
|
+
end
|
96
|
+
|
97
|
+
value = next_iter[0].next
|
98
|
+
yield(value)
|
99
|
+
break if all_iters_exhausted
|
100
|
+
end
|
101
|
+
end
|
102
|
+
|
103
|
+
def iterator(value)
|
104
|
+
return enum_for(__method__, value) unless block_given?
|
105
|
+
|
106
|
+
last = 0
|
107
|
+
|
108
|
+
value.enum_for(:scan, /[\d\+]+/).each do |seq|
|
109
|
+
n, extra = seq.split('+').map(&:to_i)
|
110
|
+
v1 = last + n
|
111
|
+
|
112
|
+
if extra
|
113
|
+
v2 = (v1 + extra)
|
114
|
+
(v1..v2).each { |i| yield(i) }
|
115
|
+
last = v2
|
116
|
+
else
|
117
|
+
yield(v1)
|
118
|
+
last = v1
|
119
|
+
end
|
120
|
+
end
|
121
|
+
end
|
122
|
+
end
|
123
|
+
end
|
data/wordmap.gemspec
ADDED
@@ -0,0 +1,28 @@
|
|
1
|
+
require_relative 'lib/wordmap/version'
|
2
|
+
|
3
|
+
Gem::Specification.new do |spec|
|
4
|
+
spec.name = 'wordmap'
|
5
|
+
spec.version = Wordmap::VERSION
|
6
|
+
spec.authors = ['Maxim Chernyak']
|
7
|
+
spec.email = ['madfancier@gmail.com']
|
8
|
+
|
9
|
+
spec.summary = 'Look up data from disk without using your RAM.'
|
10
|
+
spec.description = 'Wordmap is a simple way to lookup data directly from disk, bypassing RAM completely. It uses sysseek and sysread (no buffering), and takes advantage of SSD\'s constant seek time. The data is stored in equal size "cells" making it easy to calculate where things are located based on vectors.'
|
11
|
+
spec.homepage = 'https://github.com/scottscheapflights/wordmap'
|
12
|
+
spec.license = 'Apache-2.0'
|
13
|
+
|
14
|
+
spec.metadata['homepage_uri'] = spec.homepage
|
15
|
+
spec.metadata['source_code_uri'] = spec.homepage
|
16
|
+
spec.metadata['changelog_uri'] = 'https://github.com/scottscheapflights/wordmap/blob/master/CHANGELOG.md'
|
17
|
+
|
18
|
+
spec.required_ruby_version = Gem::Requirement.new('>= 2.4.0')
|
19
|
+
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
|
20
|
+
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^spec/}) }
|
21
|
+
end
|
22
|
+
spec.require_paths = ['lib']
|
23
|
+
|
24
|
+
spec.add_development_dependency 'bundler', '~> 2.1'
|
25
|
+
spec.add_development_dependency 'rake', '~> 13.0'
|
26
|
+
spec.add_development_dependency 'rspec', '~> 3.9'
|
27
|
+
spec.add_development_dependency 'pry', '~> 0.13'
|
28
|
+
end
|
metadata
ADDED
@@ -0,0 +1,122 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: wordmap
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Maxim Chernyak
|
8
|
+
autorequire:
|
9
|
+
bindir: bin
|
10
|
+
cert_chain: []
|
11
|
+
date: 2020-09-09 00:00:00.000000000 Z
|
12
|
+
dependencies:
|
13
|
+
- !ruby/object:Gem::Dependency
|
14
|
+
name: bundler
|
15
|
+
requirement: !ruby/object:Gem::Requirement
|
16
|
+
requirements:
|
17
|
+
- - "~>"
|
18
|
+
- !ruby/object:Gem::Version
|
19
|
+
version: '2.1'
|
20
|
+
type: :development
|
21
|
+
prerelease: false
|
22
|
+
version_requirements: !ruby/object:Gem::Requirement
|
23
|
+
requirements:
|
24
|
+
- - "~>"
|
25
|
+
- !ruby/object:Gem::Version
|
26
|
+
version: '2.1'
|
27
|
+
- !ruby/object:Gem::Dependency
|
28
|
+
name: rake
|
29
|
+
requirement: !ruby/object:Gem::Requirement
|
30
|
+
requirements:
|
31
|
+
- - "~>"
|
32
|
+
- !ruby/object:Gem::Version
|
33
|
+
version: '13.0'
|
34
|
+
type: :development
|
35
|
+
prerelease: false
|
36
|
+
version_requirements: !ruby/object:Gem::Requirement
|
37
|
+
requirements:
|
38
|
+
- - "~>"
|
39
|
+
- !ruby/object:Gem::Version
|
40
|
+
version: '13.0'
|
41
|
+
- !ruby/object:Gem::Dependency
|
42
|
+
name: rspec
|
43
|
+
requirement: !ruby/object:Gem::Requirement
|
44
|
+
requirements:
|
45
|
+
- - "~>"
|
46
|
+
- !ruby/object:Gem::Version
|
47
|
+
version: '3.9'
|
48
|
+
type: :development
|
49
|
+
prerelease: false
|
50
|
+
version_requirements: !ruby/object:Gem::Requirement
|
51
|
+
requirements:
|
52
|
+
- - "~>"
|
53
|
+
- !ruby/object:Gem::Version
|
54
|
+
version: '3.9'
|
55
|
+
- !ruby/object:Gem::Dependency
|
56
|
+
name: pry
|
57
|
+
requirement: !ruby/object:Gem::Requirement
|
58
|
+
requirements:
|
59
|
+
- - "~>"
|
60
|
+
- !ruby/object:Gem::Version
|
61
|
+
version: '0.13'
|
62
|
+
type: :development
|
63
|
+
prerelease: false
|
64
|
+
version_requirements: !ruby/object:Gem::Requirement
|
65
|
+
requirements:
|
66
|
+
- - "~>"
|
67
|
+
- !ruby/object:Gem::Version
|
68
|
+
version: '0.13'
|
69
|
+
description: Wordmap is a simple way to lookup data directly from disk, bypassing
|
70
|
+
RAM completely. It uses sysseek and sysread (no buffering), and takes advantage
|
71
|
+
of SSD's constant seek time. The data is stored in equal size "cells" making it
|
72
|
+
easy to calculate where things are located based on vectors.
|
73
|
+
email:
|
74
|
+
- madfancier@gmail.com
|
75
|
+
executables: []
|
76
|
+
extensions: []
|
77
|
+
extra_rdoc_files: []
|
78
|
+
files:
|
79
|
+
- ".github/workflows/rspec.yml"
|
80
|
+
- ".gitignore"
|
81
|
+
- ".rspec"
|
82
|
+
- CODE_OF_CONDUCT.md
|
83
|
+
- Gemfile
|
84
|
+
- LICENSE
|
85
|
+
- README.md
|
86
|
+
- Rakefile
|
87
|
+
- bin/console
|
88
|
+
- bin/setup
|
89
|
+
- lib/wordmap.rb
|
90
|
+
- lib/wordmap/access.rb
|
91
|
+
- lib/wordmap/builder.rb
|
92
|
+
- lib/wordmap/file_access.rb
|
93
|
+
- lib/wordmap/index_value.rb
|
94
|
+
- lib/wordmap/version.rb
|
95
|
+
- wordmap.gemspec
|
96
|
+
homepage: https://github.com/scottscheapflights/wordmap
|
97
|
+
licenses:
|
98
|
+
- Apache-2.0
|
99
|
+
metadata:
|
100
|
+
homepage_uri: https://github.com/scottscheapflights/wordmap
|
101
|
+
source_code_uri: https://github.com/scottscheapflights/wordmap
|
102
|
+
changelog_uri: https://github.com/scottscheapflights/wordmap/blob/master/CHANGELOG.md
|
103
|
+
post_install_message:
|
104
|
+
rdoc_options: []
|
105
|
+
require_paths:
|
106
|
+
- lib
|
107
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
108
|
+
requirements:
|
109
|
+
- - ">="
|
110
|
+
- !ruby/object:Gem::Version
|
111
|
+
version: 2.4.0
|
112
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
113
|
+
requirements:
|
114
|
+
- - ">="
|
115
|
+
- !ruby/object:Gem::Version
|
116
|
+
version: '0'
|
117
|
+
requirements: []
|
118
|
+
rubygems_version: 3.1.2
|
119
|
+
signing_key:
|
120
|
+
specification_version: 4
|
121
|
+
summary: Look up data from disk without using your RAM.
|
122
|
+
test_files: []
|