2016-12-24 77 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