Database Reference
In-Depth Information
Well, that's not a bad result for a fairly minimal amount of code. But, we can do
better:
• This solution doesn't scale well. Searching like this works by comparing the
query string with each word in the text: all
LINE
elements are string-searched for
the search phrase. When you get more and more data, the searches will become
slower and slower.
• It searches for literal strings, which means it's case-sensitive and will also return
results where the search phrase is part of a word (e.g., searching for
faun
will also
return lines with
fauna
).
• It cannot handle search
expressions
(e.g., searching for lines with
fantasy
and
Macbeth
).
So, let's add a second search facility with some enhancements.
Searching Using an Index
An index in a database is comparable to the index in a topic: it allows you to quickly
find something based on an index
key
. Although useful and often even necessary,
using indexes is not without disadvantages: it slows down creating and updating data
and consumes (a little bit of) disk space. However, indexes make searching
much
faster, especially for large collections of documents.
eXist supports several types of indexes, which we will elaborate on in Chapters
Chap‐
ter 11
and
Chapter 12
. In this example we're going to use a full-text index.
To illustrate things, let's first add all the code before creating the index. Again, we
have to change
plays_home.xq
and add a new search form. Reopen
plays-home.xq
(
Example 3-6
) and add the following lines right before the closing
</body>
element:
<br/>
<h3>
Search using index:
</h3>
<form
method=
"POST"
action=
"search-2.xq"
>
<input
type=
"text"
name=
"searchphrase"
size=
"40"
/>
<input
type=
"submit"
value=
"Search!"
/>
</form>
Now create
search-2.xq
, as shown in
Example 3-9
. It's almost the same as
search-1.xq
(
Example 3-8
), so copy, paste, and fiddle is probably a good option here.
Example 3-9. Search page that uses indexed search
xquery
version
"3.0"
;
declare
option
exist:serialize
"method=xhtml media-type=text/html"
;
declare
variable
$
page-title
:=
"Search results with XQuery using full-text index"
;
declare
variable
$
searchphrase
:=
request:get-parameter
(
"searchphrase"
,
());
Search WWH ::
Custom Search