XQuery/Basic Search
Contents |
Motivation [edit]
You want to create a basic HTML search page and search service.
Method [edit]
We will create two files. One is an HTML form and the other is a RESTful search service that takes a single parameter from the URL which is the search query. The search service will search a collection of XML files.
Here is the base path to our test search collection:
/db/test/search
The data to be searched will be in the following collection:
/db/test/search/data
In "Browse Collections" in the Admin interface, create the collection "test"; create the collection "search" under it; lastly, create the collection "data" under "search". Upload the two XML documents listed under "Sample Data" to "data"; upload "search-form.xq" and "search.xq" to "search" (instead of uploading, you can Save to URL, using oXygen, or use the Webstart client).
Search Form [edit]
/db/test/search/search-form.xq [edit]
We will create a basic HTML form that has just one input field for the query.
declare option exist:serialize "method=xhtml media-type=text/html indent=yes"; let $title := 'Basic Search Form' return <html> <head> <title>{$title}</title> </head> <body> <h1>{$title}</h1> <form method="GET" action="search.xq"> <p> <strong>Keyword Search:</strong> <input name="q" type="text"/> </p> <p> <input type="submit" value="Search"/> </p> </form> </body> </html>
Note that the action will pass the value from the form to a RESTful service. The only parameter will be "q", the query string.
Search Service [edit]
The following file should be placed in /db/test/search/search.xq
/db/test/search/search.xq [edit]
xquery version "1.0";
declare option exist:serialize "method=xhtml media-type=text/html indent=yes";
let $title := 'Simple Search RESTful Service'
let $data-collection := '/db/test/search/data'
(: get the search query string from the URL parameter :)
let $q := request:get-parameter('q', '')
return
<html>
<head>
<title>{$title}</title>
</head>
<body>
<h1>Search Results</h1>
<p><b>Searching for: </b>{$q} in collection: {$data-collection}</p>
<ol>{
for $fruit in collection($data-collection)/item[fruit/text() = $q]
return
<li>{data($fruit)}</li>
}</ol>
</body>
</html>
Running your Search [edit]
To test your search service from a URL, copy the following into the browser navigation toolbar:
http://localhost:8080/exist/rest/db/test/search/search.xq?q=apple
You should see the following result:
To drive this service from a form, click the following link or copy it into your browser navigation toolbar:
http://localhost:8080/exist/rest/db/test/search/search-form.xq
Sample Data for /db/test/search/data [edit]
/db/test/search/data/1.xml [edit]
<item> <fruit>apple</fruit> </item>
/db/test/search/data/2.xml [edit]
<item> <fruit>banana</fruit> </item>
This page may need to be 
