faceted-search.xqm 12.5 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
4

import module namespace kwic="http://exist-db.org/xquery/kwic";
Mathias Goebel's avatar
Mathias Goebel committed
5
import module namespace config="https://sade.textgrid.de/ns/config" at "config.xqm";
Mathias Goebel's avatar
Mathias Goebel committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

declare namespace tei="http://www.tei-c.org/ns/1.0";
declare namespace bol="http://blumenbach-online.de/blumenbachiana";
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"))
    let $target := config:get("data-dir")
    let $hits := local:get-hits($model, $target)
    let $obreq := request:get-parameter("order-by", "relevance")
    let $order-by := string-join($config:configDoc//module[@key="faceted-search"]//order[@key = $obreq]//xpath , ",")
    let $hitsordered :=
        if(request:get-parameter("order", "descending") = "descending") then
                for $hit in $hits
                order by util:eval($order-by) descending
                return $hit
            else
                for $hit in $hits
                order by util:eval($order-by) ascending
                return $hit

Mathias Goebel's avatar
Mathias Goebel committed
27
    let $num :=  try{ xs:integer(config:get("hits-per-page", "faceted-search")) } catch * {0}
Mathias Goebel's avatar
Mathias Goebel committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
    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
44
    let $query := request:get-parameter("q", ())
Mathias Goebel's avatar
Mathias Goebel committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
    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
63
    let $num := try { xs:integer(config:get("hits-per-page", "faceted-search")) } catch * {0}
Mathias Goebel's avatar
Mathias Goebel committed
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
    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
83
    let $viewdoc := config:get('viewer-html', 'faceted-search')
Mathias Goebel's avatar
Mathias Goebel committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97

    return
        <a href="{$viewdoc}{util:document-name($model("hit"))}">
            {
                for $titleQuery in $config:configDoc//module[@key="faceted-search"]/param[@key="result-title"]//xpath
                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
98
99
    let $link := config:get('viewer-html','faceted-search') || $docname
    let $xslt := config:get('result-xslt','faceted-search')
Mathias Goebel's avatar
Mathias Goebel committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120

    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(*)) {
    (:  TODO: could better be done in template, than by param :)
Mathias Goebel's avatar
Mathias Goebel committed
121
    if(xs:boolean(config:get( "thumbnail","faceted-search"))) then
Mathias Goebel's avatar
Mathias Goebel committed
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
        (: 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
            ()
};

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
137
    let $kwic-width := config:get("faceted-search", "kwic-width")
Mathias Goebel's avatar
Mathias Goebel committed
138
139
    order by ft:score($hit) descending
    return
Mathias Goebel's avatar
minor    
Mathias Goebel committed
140
        for $i in 1 to xs:integer(config:get("kwic-hits", "faceted-search"))
Mathias Goebel's avatar
Mathias Goebel committed
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
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
        return
            if(($expanded//exist:match)[$i]) then
                kwic:get-summary($expanded, ($expanded//exist:match)[$i], <config width="{$kwic-width}"/>)
            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(
        for $facet in $config:configDoc//module[@key="faceted-search"]//facet
        return
            map:entry(xs:string($facet/@key), local:facet($model, $hits, $facet/@key, $facet//xpath/text()))
    )
};

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()* {
  let $facets := $config:configDoc//module[@key="faceted-search"]//facet

  for $facet in $facets
      (: hide facet-categories with less than one entry :)
      where (count($model("facets")(xs:string($facet/@key))) > 0)
      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>

    let $xqueries :=  for $query-root in $config:configDoc//module[@key="faceted-search"]/param[@key="query-root"]//xpath
        return
            if($query) then
                "collection($target)" || $query-root || $fxquery || "[ft:query(., $query, $options)]"
            else
                "collection($target)" || $query-root || $fxquery

    let $xquery := string-join($xqueries, " | ")
    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 :=
                    for $xpath in $config:configDoc//module[@key="faceted-search"]//facet[@key = $parts[1]]//xpath

                        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)
};