Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching multiple strings in all fields in Elasticsearch using Java API

I've an elasticsearch index having users with fields like.. "name" : "kai" "age" : "23" "location" : "Delhi, India" "tag": [ "search", "nosql" ] etc.

I want to query multiple strings in all fields of user (Eg. ["nosql","delhi"]). Is it possible using Java API?

Here is a sample of code I am using. (But it is irrelevant to the question) Its just to know the objects I am using right now.

BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.matchAllQuery());
        if(location!=null) {
            queryBuilder.must(QueryBuilders.matchQuery("location",location));
        }
        BoolFilterBuilder filerBuilder=FilterBuilders.boolFilter();     
        for(String skill:skills){
            filerBuilder.must(FilterBuilders.rangeFilter("tags."+skill).from(0));
        }
        filerBuilder.must(FilterBuilders.queryFilter(queryBuilder));
        if(age!=null) {
            filerBuilder.must(FilterBuilders.rangeFilter("age").from(age[0]).to(age[1]));
        }
        SearchResponse response = client.prepareSearch("skillbin")
                .setTypes("stackdump")
                .setSearchType(SearchType.QUERY_AND_FETCH)
                .setQuery(queryBuilder)   
                .setPostFilter(filerBuilder)
                .addSort("reputation", SortOrder.DESC)
                .execute()
                .actionGet();
        SearchHits hits=response.getHits(); 

Thanks in advance. :)

like image 443
Krishnalal P Avatar asked Dec 02 '14 07:12

Krishnalal P


2 Answers

In Java API, you can query against "_all" field, which by default include all the fields of a document. An alternative way is use MultiMatchQuery which is more flexible and allows you to specify a list of fields you want to query against.

Here is some sample code on how to access "_all" field as well as how to create a MultiMatchQuery by using MultiMatchQueryBuilder and QueryBuilders.multiMatchQuery along a query to search in all the fields:

String queryString = "nosql delhi";

String allField = "_all";

MultiMatchQueryBuilder mmqb = QueryBuilders.multiMatchQuery(queryString, allField);
like image 172
hexabunny Avatar answered Oct 18 '22 05:10

hexabunny


If you're using standard analyzer, elasticsearch tokenizes every word by default using white space tokenizer.

You can use query string query for your search in that case, where you can add multiple fields to search in. Also query string query's default operator is "OR". So if your search term is "nosql delhi" (as in your case), it is translated into "nosql OR delhi" and searched in all the fields specified in the query. This way you can search multiple terms in multiple fields.

Hope that helps.

like image 29
Natzy8 Avatar answered Oct 18 '22 06:10

Natzy8