Search our Blogs
Showing results for 
Search instead for 
Do you mean 
 

Powerful and feature-rich Search APIs for Android apps

One of the biggest frustrations users complain about is the limited or non-existent search functionality in their apps. With the explosion of data (particularly on smartphones that both generate and consume incredible volumes and variety of data) this should not be surprising to any app developer, and users now demand Intelligent Search across all their apps.

HPE Haven OnDemand provides an extensive collection of over 70 APIs that you can use to build Enterprise Class cognitive search solutions that return the best results from both the Haven OnDemand public text indexes as well as from any private text indexes you create with a single API call.

You can index your own data directly using the Unstructured Text Indexing APIs or on a schedule using the Connector APIs (which also make the job of connecting and maintaining indexed data from websites, files systems, SharePoint and DropBox almost as easy as 1-2-3). Read this blog if you want to learn how to build a DropBox connector.

 

In this blog, I will show you how to call Haven OnDemand Query Text Index API from an Android application to search for information from Wikipedia via Haven OnDemand public datasets. This should give you a solid foundation for starting your project to add Intelligent Search to your Android apps using the Haven OnDemand. While this tutorial only covers the basic implementation of the Query Text Index API, there are many advanced configurations you can utilize to create your Intelligent Search experience.

 

Getting started

If you are new to Haven OnDemand, please click here to create an account. Once your account is setup, click here to copy the API key so you can use it to call Haven OnDemand APIs.

 

Requirements

  • Make sure that you have the Android Studio 2.x IDE installed in your environment.
  • You are familiar with using Android Studio and know how to build an Android application project.

To keep this blog easy to read, I will skip discussions about how to add, initialize and implement UI elements such as EditText, Spinner and ListView UI components being used in the demo app. Also, the demo code in this blog is just for illustration and might not appear in proper class structure. Click here to download the complete app project.

 

Create the Android app

Let’s start by creating an Android app called WikipediaSearch with an empty activity named MainActivity.

For convenience, we will install the Haven OnDemand library for Android so we can easily call Haven OnDemand APIs. To integrate the library into our project, we open the application build.gradle file and add the compile lines to the dependencies block as shown below:

dependencies {
    compile (‘com.havenondemand:hodclient:2.1’)
    compile (‘com.havenondemand:hodresponseparser:2.1’)
}

 

 

Now open the MainActivity.java file and import the Haven OnDemand library packages.

import hod.api.hodclient.*;
import hod.response.parser.*;

 

 

Then from the MainActivity class where we will implement the search feature, we extend the ListActivity and implement the IHODClientCallback interface. Please read the README content for detailed descriptions of the callback functions.

 

public class MainActivity extends ListActivity implements IHODClientCallback
{
    @Override
    public void onErrorOccurred(String errorMessage) { }
    @Override
    public void requestCompletedWithJobID(String response) { }
    @Override
    public void requestCompletedWithContent(String response) { }
}

 

 

We will need a few UI components for taking user inputs and displaying the search result.

An edit text field for users to type in search words

   

private EditText mSearchEt;

 

 

A Spinner list for users to select a language

   

private Spinner mWikiLanguageSp;

 

 

A list view to display search results

   

private ListView mItemList;

 

 

We also create a data class named QTIResp (short hand for QueryTextIndexResponse) where we have a list of Document object.

public class QTIResp {
        public List<Document> documents;
        public class Document {
            public String reference;
            public Double weight;
            public String title;
            public String summary;
        }
    }

 

 

Finally, we declare the HODClient and HODResponseParser class objects  

   

private HODClient mHodClient;

 

 

To see how the UI components and object variables above are created, initialized, and implemented, please have a look at the onCreate() and onResume() functions from the demo project code.

Call the Query Text Index API

Whenever a user writes search text into the mSearchEt field and presses the Enter key, we will call the SearchWikipedia function.

private void SearchWikipedia()
{
    String searchArg = mSearchEt.getText().toString();
    if (searchArg.length() == 0)
        searchArg = "*";
    if (m_templates.size() > 0) {
        m_templates.clear();
        m_adapter.notifyDataSetChanged();
    }
    String lang = mWikiLanguageSp.getSelectedItem().toString();
    String indexName = mLanguages.get(lang);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("text", searchArg);
    params.put("indexes", indexName);
    params.put("summary", "quick");
    params.put("absolute_max_results", "100");
    String hodApp = HODApps.QUERY_TEXT_INDEX;
    mHodClient.GetRequest(params, hodApp, HODClient.REQ_MODE.SYNC);
}

 

 

First, we read the user input text from the mSearchEt field and check the length of the searchArg If the searchAgr is empty, then we assign an asterick “*” to the searchArg to search for everything.

We will detect the language a user has selected from the mWikiLanguageSp list then look up from the mLanguages table to specify the text indexName.

Then, we create a params HashMap and pack the parameters as shown above. The “text” field holds the search text, the “indexes” field holds the user selected index name. We also set the value “quick” for the “summary” field so we will receive the first few lines from the content of a document if found. The last parameter “absolute_max_results” is set to 100 to define the maximum number of items should it returns from the API.

Finally we use the mHodClient.GetRequest method to call the Query Text Index API.

 

Parse the JSON response and display search result

When the requestCompletedWithContent callback function is called, we will receive a JSON response.

@Override
public void requestCompletedWithContent(String r) {
    QTIResp resp = (QTIResp) mParser.ParseCustomResponse(QTIResp.class, r);
    if (resp != null) {
        if (resp.documents.size() == 0) {
            Toast.makeText(this, "Not found", Toast.LENGTH_LONG).show();
            return;
        }
        for (QTIResp.Document doc : resp.documents)
            m_templates.add(doc);
                
        m_adapter.notifyDataSetChanged();
    }
}

 

 

We now use the mParser.ParseCustomResponse to parse the JSON response data from the Query Text Index API into the QTIResp class object.

If the resp is not null and the resp.documents list is not empty, we will loop through the resp.documents list and add the doc to the ArrayList m_templates which is associated with the ListView UI component. Each item from the list view will contain the title of the result document, the percentage relevance that the result document has to the original query, and the summary of the result document. Each item also contain a hidden reference ID which in this case, is the URL of the original result document in the Wikipedia website.

When a user clicks on an item on the list view, we will open the original document from Wikipedia website with the code below:

    String url = m_templates.get(myItemInt).reference;
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

 

 

 

 phong.png

 

The Query Text Index API supports a lot more configuration parameters which allow you to perform advanced search. One of the most useful configuration is the field_text parameter for specifying parametric fields using field text operators. For example, you can add the following line to the code to search for only documents matching with the “place” Wikipedia_type.

params.put("fieldtext", "MATCH{place}:wikipedia_type”);

 

 

You can call the Get Parametric Values API to retrieves the parametric values of the wikipedia_type or of any other parametric fields in the dataset. You can also call the Retrieve Index Field API to retrieve a list of the fields that have been ingested into a specified text index.

Ultimately, you can query from any other Haven OnDemand public text indexes or create your own text index to build a powerful search engine for your application.

Social Media
About the Author
Topics
† The opinions expressed above are the personal opinions of the authors, not of HPE. By using this site, you accept the Terms of Use and Rules of Participation