Building and executing a query

Building and executing a query — This example builds and executes an XML query, retrieving the hit count

The Program

This example demonstrates how to build a query using an XML query builder, pass it to a search and retrieve the hit count.

#include <stdio.h>
#include <glib.h>
#include <glib-object.h>

#include <xesam-glib.h>

/* Print out the number of found hits and exit */
static void
search_done_cb (XesamGSearch *search, gpointer userdata)
{
	GMainLoop *loop;
	
	g_printf ("Search done with %d hits\n",
			  xesam_g_search_get_num_found (search));
	
	loop = (GMainLoop*) userdata;
	
	g_main_loop_quit (loop);
	
}

int
main (int argc, char *argv[])
{
	XesamGQueryBuilder	 	*builder;
	GMainLoop				*mainloop;
	XesamGSearcher			*searcher;
	XesamGSession			*session;
	XesamGSearch			*search;
	XesamGQuery				*query;
	GError					*error;
    
	g_type_init ();
	
	builder = XESAM_G_QUERY_BUILDER (xesam_g_xml_query_builder_new ());
	mainloop = g_main_loop_new (NULL,FALSE);
	searcher = XESAM_G_SEARCHER(xesam_g_dbus_searcher_new_default ());
	session = xesam_g_session_new (searcher);
	
	/* Build a query
	 * This query will match all documents in any achieve (.zip, .tgz etc.)
	 * which contain "hendrix" in the title or subject */
	xesam_g_query_builder_start_query (builder, XESAM_G_QUERY_TOKEN_QUERY,
									   "xesam:Document", "xesam:ArchivedFile",
									   NULL);
	
	xesam_g_query_builder_add_clause (builder, XESAM_G_QUERY_TOKEN_CONTAINS,
									  NULL, NULL, NULL, NULL, NULL);
	
	xesam_g_query_builder_add_field (builder, XESAM_G_QUERY_TOKEN_FIELD,
									 "xesam:title", NULL);
	
	xesam_g_query_builder_add_field (builder, XESAM_G_QUERY_TOKEN_FIELD,
									 "xesam:subject", NULL);
	
	xesam_g_query_builder_add_value (builder, XESAM_G_QUERY_TOKEN_STRING,
									 "hendrix", NULL, NULL, NULL);
	
	xesam_g_query_builder_close_clause (builder, NULL);
	xesam_g_query_builder_close_query (builder, NULL);
	
	query = xesam_g_xml_query_builder_get_query (
											XESAM_G_XML_QUERY_BUILDER(builder));
	search = xesam_g_session_new_search (session, query);
	
	/* The query is a GInitiallyUnowned and will be owned by the search now,
	 * so no need to unref it */
	
	/* Connect to signals before we start the search. We will simply exit, printing
	 * the hit count, when the 'done' signal is received */
	g_signal_connect (search, "done", G_CALLBACK(search_done_cb), mainloop);
	
	xesam_g_search_start (search);
	g_main_loop_run (mainloop);
	
	g_printf ("Bye.\n");
}

Compilation

Save the code in a file called xesam-build-search.c and compile it with

gcc $(pkg-config --libs --cflags xesam-glib) xesam-build-search.c -o xesam-build-search

Test Run

You can take the compiled program for a test run simply by running

./xesam-build-search

You will likely see output looking like this:

$ ./xesam-build-search
Search done with 50 hits
Bye.