2016-12-24 81 views
1

我是XQuery 3.0的新手,试图创建一个简单的多滤镜搜索算法。XQuery多滤镜搜索算法

我想要做的是,检查是否提供了一个参数,如果是,请将其添加到查询中。

这是我在我的脑海:

let $query := doc("music.xml")//music/album 

if (request:get-parameter('type', false)) then 
    let $query := $query[ @type=request:get-parameter('type', '') ] 
else 
    let $query := $query 

if (request:get-parameter('title', false)) then 
    let $query := $query[ @title=request:get-parameter('title', '') ] 
else 
    let $query := $query 

if (request:get-parameter('artist', false)) then 
    let $query := $query[ @artist=request:get-parameter('artist', '') ] 
else 
    let $query := $query 

这是不正确,很明显。任何帮助,使其正确?

回答

2

最简单的图案将如下,创建用于每个可能的请求参数的变量(供给各作为空序列的默认值),然后返回子句中,在检查每个参数的存在,一个时间:

xquery version "3.0"; 

let $albums := doc("music.xml")//music/album 
let $type := request:get-parameter('type',()) 
let $title := request:get-parameter('title',()) 
let $artist := request:get-parameter('artist',()) 
return 
    if ($type) then 
     $albums[type = $type] 
    else if ($title) then 
     $albums[title = $title] 
    else if ($artist) then 
     $albums[artist = $artist] 
    else 
     $albums 

此代码假定<type><title>,和<artist><album>子元素,我们检查了提供的参数完全匹配。你可以改变title = $title比较contains(title, $title)为区分大小写的文字字符串匹配,matches(title, $title, 'i')为不区分大小写的正则表达式搜索,或全文索引像ft:query(title, $title),如果你配置了索引全文索引上<title>元素等

的这种方法的弱点在于,我们对影响查询的参数进行了严格的严格优先级排序。如果提供了type参数,则即使提供titlealbum的查询也不会被考虑。

要链接在一起,这样任何和所有提供的参数进行查询,你可以采取以下方法:

xquery version "3.0"; 

let $albums := 
    <albums> 
     <album><type>country</type><title>Holiday Classics</title><artist>Jane</artist></album> 
     <album><type>country</type><title>Lonesome Cowboy</title><artist>Jim</artist></album> 
     <album><type>country</type><title>Lonesome Holiday</title><artist>Jane</artist></album> 
    </albums>//album 
let $type := request:get-parameter('type',()) 
let $title := request:get-parameter('title',()) 
let $artist := request:get-parameter('artist',()) 
return 
    $albums 
     [if ($type) then type = $type else true()] 
     [if ($title) then title = $title else true()] 
     [if ($artist) then artist = $artist else true()] 

我提供的样本数据只是为了确认自己和他人的测试,这一工作的代码。只有提供参数时才会评估return子句中的比较。此代码假设每个参数最多一个值;如果您为每个参数允许多个值,则需要进行一些调整。

+0

谢谢@joewiz,你是我的救星:) – yenerunver

+0

好听;) – joewiz