Creating A Site Search Function With CFSearch - page 2

Author: Steven Neiland
Published:

Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.

Populate From A Query Using CFIndex

Now that we have a somewhere to store our search index we now need to populate it with data. To do this we use the cfindex tag. In this case I am populating the index using the title and description of my blog entries.

Note how I specify title and description for the body as I want to use the description and blog titles only as valid search data. However I could have easily added the blog content itself or any available datapoints.

<!--- First get some data to index --->
<cfquery name="getPublishedBlogs">
      SELECT blogID,blogTitle,blogDescription
      FROM blog
      WHERE published = 1
</cfquery>

<!--- Then index it --->
<cfindex
      collection="publishedBlogs"
      action="update"
      type="custom"
      title="blogTitle"
      body="blogTitle,blogDescription"
      query="getPublishedBlogs"
      key="blogID">

When we use the action="update" attribute of the cfindex tag the key value determines if data should be over ridden or appended. This means that we can run a second update on the same index to add in new data and the old data will not be changed unless there is an existing record with the same key value in which case the old data would be over written.

Populate Index From A Directory

We can also populate our index from static files or cfml templates. To do this we specify the path to the directory containing our static pages.

<cfindex 
      collection="publishedBlogs"
      action="update"
      type="path"
      urlpath="/path/to/mysite/staticPagesDir/"
      extensions=".cfm,.html"
      key="/path/to/mysite/staticPagesDir/">

I have not tried mixing the two methods of indexing data but I believe that it is possible. (someone please correct me if I am wrong.)

Search The Index Using CFSearch

Now that we have indexed data lets run a search.

<!--- Search all published blog entries for "coldfusion rocks" and return a query resultset --->
<cfsearch name="searchResults" collection="publishedBlogs" criteria="coldfusion rocks">
<cfdump var="#searchResults#">

So there you have it. The only thing left to do is build a search form to submit to the cfsearch tag and format results nicely.

Further Reading

Adobe CF9 Docs

CFCollection, CFIndex, CFSearch

RAILO Docs

CFCollection, CFIndex, CFSearch

Other

Notes on moving from Verity to SOLR

1 2

Related Blog Postings

Reader Comments

  • Please keep comments on-topic.
  • Please do not post unrelated questions or large chunks of code.
  • Please do not engage in flaming/abusive behaviour.
  • Comments that contain advertisments or appear to be created for the purpose of link building, will not be published.

Archives Blog Listing