简体   繁体   中英

Elastic search High Level Client Equivalent for Fields Query

I have a elastic search query as follows. I want to write this query to the JAVA high level client.

{"query":{"query_string":{"query":"*123*","fields":["address"]}}}

Can anyone help regarding it? I am not able to find the equivalent of fields in High Level Client.

How about this:

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

public class Main {

    public static void main(String[] args) throws Exception {
        // Create RestHighClient
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")
                )
        );

        // Create search query using builder
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders
                .queryStringQuery("*123*")
                .field("address"));

        // Create SearchRequest
        SearchRequest request = new SearchRequest();
        request.source(builder);

        // Request
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        System.out.println(response);

        client.close();
    }
}


And the result:

{
  "took": 12,
  "timed_out": false,
  "_shards": {
    "total": 4,
    "successful": 4,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 1.0,
    "hits": [
      {
        "_index": "test-191220",
        "_type": "_doc",
        "_id": "4dxQIW8BbItIJo_OTPzv",
        "_score": 1.0,
        "_source": {
          "address": "123-456, City, Country",
          "phone": "123-456-789",
          "name": "John Doe"
        }
      }
    ]
  }
}


Sample data for your question are like below:

POST test-191220/_doc
{
  "address": "123-456, City, Country",
  "phone": "123-456-789",
  "name": "John Doe"
}

POST test-191220/_search
{
  "query": {
    "query_string": {
      "query": "*123*",
      "fields": ["address"]
    }
  }
}


You can check below link for further information:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM