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

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

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

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

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

    ()

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

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
143
    let $kwic-width := config:get("kwic-width", "faceted-search")
Mathias Goebel's avatar
Mathias Goebel committed
144
145
    order by ft:score($hit) descending
    return
Mathias Goebel's avatar
minor    
Mathias Goebel committed
146
        for $i in 1 to xs:integer(config:get("kwic-hits", "faceted-search"))
Mathias Goebel's avatar
Mathias Goebel committed
147
        return
Mathias Goebel's avatar
Mathias Goebel committed
148
            if(($expanded//exist:match)[$i]) then
149
150
151
152
                let $summary := kwic:get-summary($expanded, ($expanded//exist:match)[$i], <config width="{$kwic-width}"/>),
                    $console := console:log($summary)
                return
                    <p class="kwic"><span class="kwic-prev">{$summary/span[@class="previous"]/node()}</span> <span class="kwic-hit">{$summary/span[@class="hi"]/node()}</span> <span>{$summary/span[@class="following"]/node()}</span></p>
Mathias Goebel's avatar
Mathias Goebel committed
153
154
155
156
157
158
159
            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
Mathias Goebel's avatar
Mathias Goebel committed
160
        <a href="/exist/rest{$docloc}">{ $node/@class, $node/* }</a>
Mathias Goebel's avatar
Mathias Goebel committed
161
162
163
164
165
166
167
168
169
170
};

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
171
        for $facet in config:get("facets", "faceted-search")
Mathias Goebel's avatar
Mathias Goebel committed
172
        return
Mathias Goebel's avatar
Mathias Goebel committed
173
            map:entry($facet/string(@key), local:facet($model, $hits, $facet/string(@key), string($facet/cf:xpath/text())))
Mathias Goebel's avatar
Mathias Goebel committed
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(*)) {
Mathias Goebel's avatar
Mathias Goebel committed
183
    <li>{ map:keys($model("facet")) }</li>
Mathias Goebel's avatar
Mathias Goebel committed
184
185
186
};

declare function fsearch:facet($node as node(), $model as map(*)) as item()* {
Mathias Goebel's avatar
Mathias Goebel committed
187
188
    let $facets := config:get("facets", "faceted-search")
    for $facet in $facets
Mathias Goebel's avatar
Mathias Goebel committed
189
      (: hide facet-categories with less than one entry :)
Mathias Goebel's avatar
Mathias Goebel committed
190
      where (count($model("facets")($facet/string(@key))) > 0)
Mathias Goebel's avatar
Mathias Goebel committed
191
      return
Mathias Goebel's avatar
Mathias Goebel committed
192
193
          <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>
Mathias Goebel's avatar
Mathias Goebel committed
194
          </li>
Mathias Goebel's avatar
Mathias Goebel committed
195
};
Mathias Goebel's avatar
Mathias Goebel committed
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218

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
Mathias Goebel's avatar
Mathias Goebel committed
219
                <un>{ $norms }</un>
Mathias Goebel's avatar
Mathias Goebel committed
220
221
222
223
224
225
226
227
228
229
230
231
232
233
            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">
Mathias Goebel's avatar
Mathias Goebel committed
234
235
                            <a class="facet-minus" href="{ $search-html }?q={ $query }&amp;facet={ $facetRemoveQuery }&amp;order={ $order }&amp;order-by={ $order-by }">-</a>
                            { $facet } ({ $freq })
Mathias Goebel's avatar
Mathias Goebel committed
236
237
238
                        </li>
               else
                   <li>
Mathias Goebel's avatar
Mathias Goebel committed
239
240
                       <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 })
Mathias Goebel's avatar
Mathias Goebel committed
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
                   </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>
281
    let $xqueries :=
Mathias Goebel's avatar
Mathias Goebel committed
282
283
284
285
286
287
            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
288
289

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

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

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