faceted-search.xqm 12.9 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";
6
import module namespace console="http://exist-db.org/xquery/console";
Mathias Goebel's avatar
Mathias Goebel committed
7
8

declare namespace bol="http://blumenbach-online.de/blumenbachiana";
9
10
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
11
12
13
14
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"))
15
    let $target := $config:app-root || "/" || config:get("project-id") || "/data"
Mathias Goebel's avatar
Mathias Goebel committed
16
    let $hits := local:get-hits($model, $target)
17
18
    let $console := console:log( $hits )

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

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

    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(*)) {
125
126
127
128
129
130
131
132
133
134
135
136
137
138

    ()

(:    (:  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
139
140
141
142
143
144
};

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
145
    let $kwic-width := config:get("faceted-search", "kwic-width")
Mathias Goebel's avatar
Mathias Goebel committed
146
147
    order by ft:score($hit) descending
    return
Mathias Goebel's avatar
minor    
Mathias Goebel committed
148
        for $i in 1 to xs:integer(config:get("kwic-hits", "faceted-search"))
Mathias Goebel's avatar
Mathias Goebel committed
149
        return
150
151
            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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
            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
170
        for $facet in config:get("facets", "faceted-search")//facet
Mathias Goebel's avatar
Mathias Goebel committed
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
        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()* {
Mathias Goebel's avatar
Mathias Goebel committed
186
  let $facets := config:get("facets", "faceted-search")//facet
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

  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)
276
    let $console := console:log( $fxquery )
Mathias Goebel's avatar
Mathias Goebel committed
277
278
279
280
281

    let $options :=
        <options>
            <leading-wildcard>yes</leading-wildcard>
        </options>
282
283
284
    let $console := console:log( config:get("query-root", "faceted-search") )
    let $xqueries :=
    for $query-root in config:get("query-root", "faceted-search")
Mathias Goebel's avatar
Mathias Goebel committed
285
286
287
288
289
290
291
        return
            if($query) then
                "collection($target)" || $query-root || $fxquery || "[ft:query(., $query, $options)]"
            else
                "collection($target)" || $query-root || $fxquery

    let $xquery := string-join($xqueries, " | ")
292
293
    let $console := console:log( $xquery )

Mathias Goebel's avatar
Mathias Goebel committed
294
295
296
297
298
299
300
301
302
303
304
305
    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 :=
Mathias Goebel's avatar
Mathias Goebel committed
306
                    for $xpath in config:get("facets", "faceted-search")//facet[@key = $parts[1]]//xpath
Mathias Goebel's avatar
Mathias Goebel committed
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
345
346
347
348
349
350
351
352

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