faceted-search.xqm 12.7 KB
Newer Older
Mathias Goebel's avatar
Mathias Goebel committed
1
xquery version "3.1";
Mathias Goebel's avatar
Mathias Goebel committed
2
module namespace fsearch="https://sade.textgrid.de/ns/faceted-search";
Mathias Goebel's avatar
Mathias Goebel committed
3

Mathias Goebel's avatar
Mathias Goebel committed
4
import module namespace config="https://sade.textgrid.de/ns/config" at "config.xqm";
Mathias Goebel's avatar
Mathias Goebel committed
5
import module namespace kwic="http://exist-db.org/xquery/kwic";
Mathias Goebel's avatar
Mathias Goebel committed
6
7

declare namespace bol="http://blumenbach-online.de/blumenbachiana";
8
9
declare namespace cf="https://sade.textgrid.de/ns/configfile";
declare namespace tei="http://www.tei-c.org/ns/1.0";
Mathias Goebel's avatar
Mathias Goebel committed
10
11
12
13
declare namespace templates="http://exist-db.org/xquery/templates";

declare function fsearch:results($node as node(), $model as map(*)) as map()* {
    let $page := xs:integer(request:get-parameter("page", "1"))
14
    let $target := $config:app-root || "/" || config:get("project-id") || "/data"
Mathias Goebel's avatar
Mathias Goebel committed
15
    let $hits := local:get-hits($model, $target)
16

Mathias Goebel's avatar
Mathias Goebel committed
17
    let $obreq := request:get-parameter("order-by", "relevance")
Mathias Goebel's avatar
Mathias Goebel committed
18
(:    let $order-by := string-join($config:configDoc//module[@key="faceted-search"]//order[@key = $obreq]//xpath , ","):)
Mathias Goebel's avatar
Mathias Goebel committed
19
20
21
    let $hitsordered :=
        if(request:get-parameter("order", "descending") = "descending") then
                for $hit in $hits
Mathias Goebel's avatar
Mathias Goebel committed
22
(:                order by util:eval($order-by) descending:)
Mathias Goebel's avatar
Mathias Goebel committed
23
24
25
                return $hit
            else
                for $hit in $hits
Mathias Goebel's avatar
Mathias Goebel committed
26
(:                order by util:eval($order-by) ascending:)
Mathias Goebel's avatar
Mathias Goebel committed
27
28
                return $hit

Mathias Goebel's avatar
Mathias Goebel committed
29
    let $num :=  try{ xs:integer(config:get("hits-per-page", "faceted-search")) } catch * {0}
Mathias Goebel's avatar
Mathias Goebel committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    let $pages := try { ceiling(count($hits) div $num) } catch * { 0 }
    let $start := $page * $num - $num + 1

    return
        map {
            "facets" := fsearch:facets($model, $hits),
            "hits" := subsequence($hitsordered,$start,$num),
            "totalhits" := count($hits),
            "start" := $start,
            "page" := $page,
            "pages" := $pages
        }
};

declare
function fsearch:searchquery($node as node(), $model as map(*)) {
Mathias Goebel's avatar
Mathias Goebel committed
46
    let $query := request:get-parameter("q", ())
Mathias Goebel's avatar
Mathias Goebel committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
    return <input type="text" value="{$query}" name="q" class="form-control" />
};

declare
    %templates:wrap
function fsearch:hitcount($node as node(), $model as map(*)) {
    $model("totalhits")
};

declare
    %templates:wrap
function fsearch:hitstart($node as node(), $model as map(*)) {
    $model("start")
};

declare
    %templates:wrap
function fsearch:hitend($node as node(), $model as map(*)) {
Mathias Goebel's avatar
Mathias Goebel committed
65
    let $num := try { xs:integer(config:get("hits-per-page", "faceted-search")) } catch * {0}
Mathias Goebel's avatar
Mathias Goebel committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
    let $res := $model("start") + $num - 1
    return if($res > $model("totalhits"))
        then $model("totalhits")
        else $res
};

declare
    %templates:wrap
function fsearch:page($node as node(), $model as map(*)) {
    $model("page")
};

declare
    %templates:wrap
function fsearch:pages($node as node(), $model as map(*)) {
    $model("pages")
};

declare function fsearch:result-title($node as node(), $model as map(*)) {
Mathias Goebel's avatar
Mathias Goebel committed
85
    let $viewdoc := config:get('viewer-html', 'faceted-search')
Mathias Goebel's avatar
Mathias Goebel committed
86
87
88
89

    return
        <a href="{$viewdoc}{util:document-name($model("hit"))}">
            {
90
                for $titleQuery in config:get("result-title", "faceted-search")//cf:xpath
Mathias Goebel's avatar
Mathias Goebel committed
91
92
93
94
95
96
97
98
99
                return util:eval("($model('hit')" || $titleQuery || ")[1]")
            }
        </a>
};

declare function fsearch:result-xslt($node as node(), $model as map(*)) {

    let $docname := util:document-name($model("hit"))
    let $id := substring-before($docname, ".")
Mathias Goebel's avatar
Mathias Goebel committed
100
    let $link := config:get('viewer-html','faceted-search') || $docname
101
    let $xslt := $config:app-root || "/" || config:get('result-xslt','faceted-search')
Mathias Goebel's avatar
Mathias Goebel committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

    let $docpath := config:get("data-dir") || "/xml/data/" || $docname
    let $title := doc($docpath)//tei:fileDesc/tei:titleStmt/tei:title

    return
        transform:transform($model("hit"), doc($xslt),
            <parameters>
                <param name="id" value="{$id}"/>
                <param name="link" value="{$link}"/>
                <param name="title" value="{$title}"/>
            </parameters>
        )

};

declare function fsearch:result-score($node as node(), $model as map(*)) {
    ft:score($model('hit'))
};

declare function fsearch:result-img($node as node(), $model as map(*)) {
122
123
124
125
126
127
128
129
130
131
132
133
134
135

    ()

(:    (:  TODO: could better be done in template, than by param :):)
(:    if(xs:boolean(config:get( "thumbnail","faceted-search"))) then:)
(:        (: TODO image-xpath should be configured by conf.xml:):)
(:        let $src := $model("hit")//bol:kerndaten/bol:mediafiles//bol:mediafile[1]/@file_uri || ($model("hit")//tei:pb)[1]/@facs:)
(:        return:)
(:            if(string-length($src) > 0) then:)
(:                <img src="{config:get("digilib.url")}{$src}{config:get("digilib.thumbnailparam")}"/>:)
(:            else:)
(:                ():)
(:        else:)
(:            ():)
Mathias Goebel's avatar
Mathias Goebel committed
136
137
138
139
140
141
};

declare function fsearch:result-kwic($node as node(), $model as map(*)) {

    let $hit := $model("hit")
    let $expanded := kwic:expand($hit)
Mathias Goebel's avatar
Mathias Goebel committed
142
    let $kwic-width := config:get("faceted-search", "kwic-width")
Mathias Goebel's avatar
Mathias Goebel committed
143
144
    order by ft:score($hit) descending
    return
Mathias Goebel's avatar
minor    
Mathias Goebel committed
145
        for $i in 1 to xs:integer(config:get("kwic-hits", "faceted-search"))
Mathias Goebel's avatar
Mathias Goebel committed
146
        return
147
148
            if(($expanded//exist:match)[$i]) then ()
(:                kwic:get-summary($expanded, ($expanded//exist:match)[$i], <config width="{$kwic-width}"/>):)
Mathias Goebel's avatar
Mathias Goebel committed
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
            else ()
};

declare function fsearch:result-source($node as node(), $model as map(*)) {

    let $docloc := config:get("data-dir") || "/xml/data/" || util:document-name($model("hit"))
    return
        <a href="/exist/rest{$docloc}">{$node/@class, $node/* }</a>
};

declare
(:    %templates:wrap:)
function fsearch:result-id($node as node(), $model as map(*)) {
    element { node-name($node) } { attribute name { util:document-name($model("hit")) }, $node/@*, $node/* }
};

declare function fsearch:facets($model as map(*), $hits) as map() {
    map:new(
Mathias Goebel's avatar
Mathias Goebel committed
167
        for $facet in config:get("facets", "faceted-search")
Mathias Goebel's avatar
Mathias Goebel committed
168
        return
Mathias Goebel's avatar
Mathias Goebel committed
169
            map:entry($facet/string(@key), local:facet($model, $hits, $facet/string(@key), string($facet/cf:xpath/text())))
Mathias Goebel's avatar
Mathias Goebel committed
170
171
172
173
174
175
176
177
178
179
180
181
182
    )
};

declare function fsearch:list-facets($node as node(), $model as map(*)) as map(*){
    map { "facetgroups" := $model("facet") }
};

declare
function fsearch:facet-title($node as node(), $model as map(*)) {
    <li>{map:keys($model("facet"))}</li>
};

declare function fsearch:facet($node as node(), $model as map(*)) as item()* {
Mathias Goebel's avatar
Mathias Goebel committed
183
184
    let $facets := config:get("facets", "faceted-search")
    for $facet in $facets
Mathias Goebel's avatar
Mathias Goebel committed
185
      (: hide facet-categories with less than one entry :)
Mathias Goebel's avatar
Mathias Goebel committed
186
      where (count($model("facets")($facet/string(@key))) > 0)
Mathias Goebel's avatar
Mathias Goebel committed
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
      return
          <li><strong>{xs:string($facet/@title)}</strong>
              <ul class="hideMore">{local:deselected-for-key($model, xs:string($facet/@key))}{$model("facets")(xs:string($facet/@key))}</ul>
          </li>
  };

declare function local:facet($model as map(*), $hits as node()*, $key as xs:string, $types as xs:string*) as node()* {

    let $query := request:get-parameter("q", ())
    let $order := request:get-parameter("order", ())
    let $order-by := request:get-parameter("order-by", ())
    let $facetReq := local:facet-query-from-request()

    (: the link to the html page displaying this module :)
    let $search-html := tokenize(request:get-url(), "/")[last()]

    (:construct xpath, e.g. $hits//tei:persName | $hits//bol:a0 :)
    let $fqueries := for $type in $types
        return concat("$hits", "//", $type)

    let $fquery := string-join($fqueries, " |")

    (: normalize strings :)
    let $unnormal := for $x in util:eval($fquery)
        return
            (:let $norms := normalize-space($x):)
            let $norms := xs:string($x)
            return if (string-length($norms) >= 1) then
                <un>{$norms}</un>
            else
                ()

    let $deselected := local:deselected-for-key($model, $key)

    for $facet in distinct-values($unnormal)
        let $freq :=  count($unnormal[. eq $facet])
        order by $freq descending
        return
            if(local:facetSelected($key, $facet))
               then
                   let $facetRemoveQuery := replace($facetReq, $key || ":" || xmldb:encode($facet) || "," , "")
                   return
                       <li class="facetSelected">
                            <a class="facet-minus" href="{$search-html}?q={$query}&amp;facet={$facetRemoveQuery}&amp;order={$order}&amp;order-by={$order-by}">-</a>
                            {$facet} ({$freq})
                        </li>
               else
                   <li>
                       <a class="facet-minus" href="{$search-html}?q={$query}&amp;facet={$key}:!{xmldb:encode($facet)},{$facetReq}&amp;order={$order}&amp;order-by={$order-by}">-</a>
                       <a href="{$search-html}?q={$query}&amp;facet={$key}:{xmldb:encode($facet)},{$facetReq}&amp;order={$order}&amp;order-by={$order-by}">{$facet}</a> ({$freq})
                   </li>

};

declare function local:deselected-for-key($model, $key as xs:string) {

    let $query := request:get-parameter("q", ())
    let $order := request:get-parameter("order", ())
    let $order-by := request:get-parameter("order-by", ())

    (: the link to the html page displaying this module :)
    let $search-html := tokenize(request:get-url(), "/")[last()]

    let $facetReq := local:facet-query-from-request()

    for $fparts in tokenize($facetReq, ",")
        let $parts := tokenize($fparts, ":")
        return if($parts[1] eq $key) then
            if(starts-with($parts[2], "!"))
                    then
                        let $facetRemoveQuery := replace($facetReq, $key || ":" || $parts[2] || "," , "")
                        return
                            <li class="facet-deselected">
                                <a class="facet-plus" href="{$search-html}?q={$query}&amp;facet={$facetRemoveQuery}&amp;order={$order}&amp;order-by={$order-by}">+</a>
                                {xmldb:decode(substring-after($parts[2], "!"))}
                            </li>
                    else
                        ()
            else ()
};

declare function local:get-hits($model as map(*), $target as xs:string) as node()*{

    let $query := request:get-parameter("q", ())
    let $fxquery := local:construct-facet-query($model)

    let $options :=
        <options>
            <leading-wildcard>yes</leading-wildcard>
        </options>
277
    let $xqueries :=
Mathias Goebel's avatar
Mathias Goebel committed
278
279
280
281
282
283
            for $query-root in config:get("query-root", "faceted-search")
            return
                if($query) then
                    "collection($target)" || $query-root || $fxquery || "[ft:query(., $query, $options)]"
                else
                    "collection($target)" || $query-root || $fxquery
Mathias Goebel's avatar
Mathias Goebel committed
284
285

    let $xquery := string-join($xqueries, " | ")
286

Mathias Goebel's avatar
Mathias Goebel committed
287
288
289
290
291
292
293
294
295
296
297
    return util:eval($xquery)
};

declare function local:construct-facet-query($model as map(*)) as xs:string {

    let $facet := local:facet-query-from-request()
    let $fxquery :=
        if ($facet) then
            for $fquery in tokenize($facet, ",")
                let $parts := tokenize($fquery, ":")
                let $select :=
298
                    for $xpath in config:get("facets", "faceted-search")//cf:facet[@key = $parts[1]]//cf:xpath
Mathias Goebel's avatar
Mathias Goebel committed
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344

                        let $val := xmldb:decode($parts[2])
                            let $op := if(starts-with($val, "!"))
                                then " ne "
                                else " eq "

                        let $val := replace($val, "!", "")

                        return if(starts-with($xpath, ".") or starts-with($xpath, "/"))
                            (: to escpae quotes, you have to double them :)
                            then $xpath || $op || """" || $val || """"
                            else ".//" || $xpath || $op || """" || $val || """"

                return
                    if(not(empty($select))) then "[" || string-join($select, " or ") || "]"
                    else ()
        else
            ()

    return string-join($fxquery, "")
};

(: we need the facet uri encoded, so request-get parameter does not work :)
declare function local:facet-query-from-request() {
    (: remove trailing questionary mark :)
    let $querystring := substring(request:get-query-string(),1)
    (: tokenize at ampersand :)
    return for $part in tokenize($querystring, codepoints-to-string(38))
        let $query := tokenize($part, "=")
            return if ($query[1] eq "facet") then
                $query[2]
            else
                ()

};

declare function local:facetSelected($key as xs:string, $value as xs:string) as xs:boolean {

    let $r := for $token in tokenize(local:facet-query-from-request(), ",")
        let $parts := tokenize($token, ":")
                return if($parts[1]=$key and xmldb:decode($parts[2])=$value)
                    then true()
                else ()

    return boolean($r)
};