字段查询的弹性搜索等效于高级客户端

时间:2019-12-20 02:03:31

标签: java elasticsearch elasticsearch-5

我有一个如下的弹性搜索查询。 我想将此查询写到JAVA高级客户端。

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

有人可以帮忙吗?我无法在“高级客户端”中找到等效的字段。

1 个答案:

答案 0 :(得分:0)

如何?

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();
    }
}


结果:

{
  "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"
        }
      }
    ]
  }
}


您的问题的样本数据如下:

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"]
    }
  }
}


您可以在下面的链接中查看更多信息: