-
Notifications
You must be signed in to change notification settings - Fork 19
/
members.clj
304 lines (257 loc) · 11.6 KB
/
members.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
(ns com.eldrix.hermes.impl.members
"Members creates a Lucene search index for reference set members."
(:require [clojure.spec.alpha :as s]
[com.eldrix.hermes.impl.search :as search]
[com.eldrix.hermes.impl.store :as store]
[clojure.core.async :as async])
(:import (org.apache.lucene.search IndexSearcher TermQuery PrefixQuery Query MatchAllDocsQuery WildcardQuery)
(org.apache.lucene.document Document Field$Store StringField LongPoint StoredField)
(java.util UUID Collection)
(java.time ZoneId LocalDate)
(org.apache.lucene.store ByteBuffersDirectory FSDirectory)
(org.apache.lucene.index IndexWriterConfig IndexWriter IndexReader DirectoryReader Term IndexWriterConfig$OpenMode)
(org.apache.lucene.analysis.standard StandardAnalyzer)
(java.nio.file Paths)))
(set! *warn-on-reflection* true)
(defn localdate->epoch-milli
"Converts a java.time.LocalDate to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z."
^long [^LocalDate date]
(.toEpochMilli (.toInstant (.atStartOfDay date (ZoneId/of "UTC")))))
(def stored-fields
"A set of field names for which we store values in the index"
#{:referencedComponentId})
(defn- make-string-field
[k v]
(StringField. (name k) (str v) (if (stored-fields k) Field$Store/YES Field$Store/NO)))
(defmulti make-fields
"Create Lucene field(s) from the value.
This could use additional runtime information if it became necessary in the
future. At the moment, we simply use the class of the value but could use
the attribute type information from the attribute reference set if required."
(fn [_k v] (class v)))
(defmethod make-fields Long [k v]
(if (stored-fields k)
[(LongPoint. (name k) (long-array [v]))
(StoredField. (name k) ^long v)]
[(LongPoint. (name k) (long-array [v]))]))
(defmethod make-fields UUID [k v]
[(make-string-field k v)])
(defmethod make-fields Boolean [k v]
[(make-string-field k v)])
(defmethod make-fields String [k v]
[(make-string-field k v)])
(defmethod make-fields LocalDate [k v]
(let [nm (name k)
v' (localdate->epoch-milli v)]
(if (stored-fields k)
[(LongPoint. nm (long-array [v']))
(StoredField. nm ^long v')]
[(LongPoint. nm (long-array [v']))])))
(defmethod make-fields Integer [k v]
(if (stored-fields k)
[(LongPoint. (name k) (long-array [v]))
(StoredField. (name k) ^long v)]
[(LongPoint. (name k) (long-array [v]))]))
(defn make-document
"Create a Lucene document representing the given reference set item.
Reference set items consist of a core set of keys and values, together with
a range of other properties for a specific subtype, or some custom properties
in a given distribution. The meaning of those properties are defined in refset
descriptors. All values are either integers, component identifiers or strings.
Currently, we do not use the runtime information made available in the refset
descriptors, as we can derive type easily by simply looking at the value."
^Document [item]
(let [doc (Document.)]
(doseq [[k v] (seq item)]
(dorun (map #(.add doc %) (make-fields k v))))
doc))
(defn open-index-writer
"Creates a Lucene index at 'filename'."
(^IndexWriter [filename]
(let [analyzer (StandardAnalyzer.)
directory (FSDirectory/open (Paths/get (str filename) (into-array String [])))
writer-config (doto (IndexWriterConfig. analyzer)
(.setOpenMode IndexWriterConfig$OpenMode/CREATE))]
(IndexWriter. directory writer-config))))
(defn build-members-index
"Build a refset members index using the SNOMED CT store at `store-filename`."
[store-filename refset-index-filename]
(let [ch (async/chan 50)]
(with-open [store (store/open-store store-filename)
writer (open-index-writer refset-index-filename)]
(store/stream-all-refset-items store ch)
(async/<!! ;; block until pipeline complete
(async/pipeline-blocking ;; pipeline for side-effects
(.availableProcessors (Runtime/getRuntime)) ;; Parallelism factor
(doto (async/chan) (async/close!)) ;; Output channel - /dev/null
(comp (map #(store/extended-refset-item store % :attr-ids? false))
(map make-document)
(map #(.addDocument writer %)))
ch))
(.forceMerge writer 1))))
(defn open-index-reader
^IndexReader [filename]
(let [directory (FSDirectory/open (Paths/get filename (into-array String [])))]
(DirectoryReader/open directory)))
(defn q-or [queries]
(search/q-or queries))
(defn q-and [queries]
(search/q-and queries))
(defn q-not
"Returns the logical query of q1 NOT q2"
[^Query q1 ^Query q2]
(search/q-not q1 q2))
(defn q-all
"Returns a query to match all documents."
[]
(MatchAllDocsQuery.))
(defn q-prefix
"Create a prefix query for the field specified."
^Query [^String field-name ^String term]
(PrefixQuery. (Term. field-name term)))
(defn q-term
"Create a query for the exact match for the field specified."
^Query [^String field-name ^String term]
(TermQuery. (Term. field-name term)))
(defn q-wildcard
"Create a wildcard query for the field specified.
From the Lucene documentation:
\"Supported wildcards are *, which matches any character sequence (including
the empty one), and ?, which matches any single character. '\\' is the
escape character. Note this query can be slow, as it needs to iterate over
many terms. In order to prevent extremely slow wildcard queries, a term
should not start with the wildcard *\"."
^Query [^String field ^String term]
(WildcardQuery. (Term. field term)))
(defn q-refset-id
"Create a query for items belonging to the reference set specified"
^Query [refset-id]
(LongPoint/newExactQuery "refsetId" refset-id))
(defn q-refset-ids
"Create a query for items belonging to the reference sets specified."
^Query [^Collection refset-ids]
(LongPoint/newSetQuery "refsetId" refset-ids))
(defn q-module-id
"Create a query for items with the specified module id"
^Query [module-id]
(LongPoint/newExactQuery "moduleId" module-id))
(defn q-module-ids
"Create a query for items with the specified module ids"
^Query [^Collection module-ids]
(LongPoint/newSetQuery "moduleId" module-ids))
(defn q-time>=
"Create a query for items with a field, or an effective time, greater or equal
than 'd'."
(^Query [d] (q-time>= "effectiveTime" d))
(^Query [^String field d] (LongPoint/newRangeQuery field (localdate->epoch-milli d) Long/MAX_VALUE)))
(defn q-time>
"Create a query for items with a field, or an effective time, greater than 'd'."
( ^Query [d] (q-time> "effectiveTime" d))
( ^Query [^String field d] (LongPoint/newRangeQuery field (inc (localdate->epoch-milli d)) Long/MAX_VALUE)))
(defn q-time=
"Create a query for items with a field, or an effective time, equal to 'd'."
(^Query [d] (q-time= "effectiveTime" d))
(^Query [^String field d] (LongPoint/newExactQuery field (localdate->epoch-milli d))))
(defn q-time<
"Create a query for items with a field, or an effective time, less than 'd'."
(^Query [d] (q-time< "effectiveTime" d))
(^Query [^String field d] (LongPoint/newRangeQuery field 0 (dec (localdate->epoch-milli d)))))
(defn q-time<=
"Create a query for items with a field, or an effective time, less than or
equal to 'd'."
(^Query [d] (q-time<= "effectiveTime" d))
(^Query [^String field d] (LongPoint/newRangeQuery field 0 (localdate->epoch-milli d))))
(defn q-time!=
"Create a query for items with a field, or an effective time, not equal to 'd'."
(^Query [d] (q-time!= "effectiveTime" d))
(^Query [^String field d]
(let [v (localdate->epoch-milli d)]
(q-or [(q-time< field (dec v)) (q-time> field (inc v))]))))
(defn q-field=
"Create a query for items with a field equal to"
[^String field ^long value]
(LongPoint/newExactQuery field value))
(defn q-field!=
"Create a query for items with a field not equal to"
[^String field ^long value]
(q-or [(LongPoint/newRangeQuery field Long/MIN_VALUE (dec value))
(LongPoint/newRangeQuery field (inc value) Long/MAX_VALUE)]))
(defn q-field<
[^String field ^long value]
(LongPoint/newRangeQuery field Long/MIN_VALUE (dec value)))
(defn q-field>
[^String field ^long value]
(LongPoint/newRangeQuery field (inc value) Long/MAX_VALUE))
(defn q-field<=
[^String field ^long value]
(LongPoint/newRangeQuery field Long/MIN_VALUE value))
(defn q-field>=
[^String field ^long value]
(LongPoint/newRangeQuery field value Long/MAX_VALUE))
(defn q-field-in
[^String field ^Collection values]
(LongPoint/newSetQuery field values))
(defn q-field-boolean
[^String field x]
(q-term field (str x)))
(defn q-referenced-component
"Create a query for items relating to the specified component."
^Query [component-id]
(LongPoint/newExactQuery "referencedComponentId" component-id))
(defn search
"Performs the search, returning a set of referenced component identifiers."
[^IndexSearcher searcher query]
(->> (search/search-all searcher query)
(map #(.doc searcher %))
(map #(.get ^Document % "referencedComponentId"))
(map #(Long/parseLong %))
set))
(defn search*
"Performs a search and returns whether result not empty.
For refset membership testing, this is an order of magnitude slower than using
the 'store' refset function.
```
(time (search-not-empty? searcher (q-and [(q-refset-id 734138000) (q-referenced-component 24700007)])))
\"Elapsed time: 2.756541 msecs\"
(time (store/get-component-refset-items store 24700007 734138000))
\"Elapsed time: 0.18375 msecs\"
```
As such, this should only be used outside of scenarios in which that cannot
be used, such as more complex or arbitrary field queries."
[^IndexSearcher searcher ^Query query]
(seq (.-scoreDocs (.search searcher query 1))))
(comment
(def store (store/open-store "snomed-2022-04-21.db/store.db"))
(.refsetFieldNames store)
(get (.refsetFieldNames store) 30931000001101)
(store/get-refset-descriptors store 30931000001101)
(store/get-refset-descriptor-attribute-ids store 30931000001101)
(store/get-preferred-synonym store 449608002 [999001261000000100])
(build-members-index "snomed.db/store.db" "snomed.db/members.db")
(def reader (open-index-reader "snomed.db/members.db"))
(def searcher (IndexSearcher. reader))
(search searcher (q-refset-id 447562003))
(search searcher (q-and [(q-prefix "mapTarget" "G21.0") (q-refset-id 447562003)]))
(time
(do (def ids (search searcher (q-and [(q-prefix "mapTarget" "G50") (q-refset-id 447562003)])))
(map #(store/get-component-refset-items store % 447562003) ids)))
(def directory (ByteBuffersDirectory.))
(def config (IndexWriterConfig. (StandardAnalyzer.)))
(def writer (IndexWriter. directory config))
(def ch (async/chan 200))
(store/stream-all-refset-items store)
(def items (async/<!! 200))
(def docs (->> items
(map #(store/extended-refset-item store % :attr-ids? false))
(map make-document)))
(dorun (map #(.addDocument writer %) docs))
(.forceMerge writer 1)
(.close writer)
(def reader (DirectoryReader/open directory))
(def searcher (IndexSearcher. reader))
(first items)
(->> (seq (.scoreDocs (.search searcher (LongPoint/newExactQuery "referencedComponentId" 100005) 20000)))
(map #(.doc searcher (.-doc %)))
(map #(.get % "referencedComponentId")))
(->> (seq (.scoreDocs (.search searcher (PrefixQuery. (Term. "mapTarget" "XU")) 1000)))
(map #(.doc searcher (.-doc %)))))