Spring Data Elasticsearch按JSON结构查询

问题描述 投票:0回答:2

我正在使用spring数据elasticsearch,当我使用@Query注释时,将代码与实际的JSON elasticsearch查询相关联要容易得多,如此链接引用中的示例所示:

https://www.programcreek.com/java-api-examples/index.php?api=org.springframework.data.elasticsearch.annotations.Query

我想知道是否有一种方法可以通过不带注释的elasticsearch java库通过完整的JSON主体进行查询。 I.E.在方法实现中或某事。这将帮助我解析响应中的突出显示等。

感谢您提供任何信息。

评论澄清:我正在使用Spring-data-elasticsearch 3.0.10.RELEASE和Elasticsearch 6.由于spring-data-elasticsearch似乎还不支持RestHighLevelClient,我使用的是TransportClient客户端= new PreBuiltTransportClient(elasticsearchSettings) ;创建ElasticsearchTemplate时的方法:return new ElasticsearchTemplate(client());

java elasticsearch spring-data-elasticsearch elasticsearch-java-api
2个回答
2
投票

我想出了一种方法,但它要求你制作一个存在于Elastic节点上的脚本。见File-based scripts。它不是非常灵活,但要试一试。这是做什么的。

创建一个名为template_doctype.mustache的文件并将其复制到$ELASTIC_HOME/config/scripts。这是您可以根据需要定制的脚本。重新启动Elastic或等待60秒以重新加载。

{
    "query" : {
        "match" : {
            "type" : "{{param_type}}"
        }
    }
}

我的pom.xml依赖项:

<dependencies>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-elasticsearch</artifactId>
        <version>3.0.10.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>transport</artifactId>
        <version>5.5.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.2</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

(仅供参考,我发现使用mvn dependency:tree,你的spring-data-elasticsearch版本隐含地使用了5.5版本的ElasticSearch库,即使你使用的是ElasticSearch 6.)

创建虚拟索引:

curl -X PUT http://localhost:9200/myindex

创建几个可用于匹配的文档以确保代码有效:

curl -X POST http://localhost:9200/myindex/mydoc -d '{"title":"foobar", "type":"book"}'
curl -X POST http://localhost:9200/myindex/mydoc -d '{"title":"fun", "type":"magazine"}'

尝试运行查询。此代码应返回单个文档:

String clusterName = "my-application";
Settings elasticsearchSettings = Settings.builder().put("cluster.name", clusterName).build();
TransportClient client = new PreBuiltTransportClient(elasticsearchSettings)
        .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"),9300));
Map<String, Object> template_params = new HashMap<>();

// Here is where you put parameters to your script.
template_params.put("param_type", "book");
SearchResponse sr = new SearchTemplateRequestBuilder(client)
        .setScript("template_doctype")  // this is where you specify what template to use
        .setScriptType(ScriptType.FILE)
        .setScriptParams(template_params)
        .setRequest(new SearchRequest())
        .get()
        .getResponse();

SearchHit[] results = sr.getHits().getHits();
for(SearchHit hit : results){

    String sourceAsString = hit.getSourceAsString();
    if (sourceAsString != null) {
        Gson gson = new GsonBuilder().setPrettyPrinting()
                .create();
        Map map = gson.fromJson(sourceAsString, Map.class);
        System.out.println( gson.toJson(map));
    }
}

输出:

{
  "title": "foobar",
  "type": "book"
}

1
投票

这是另一种方法,但不使用传输客户端。

将这些依赖项添加到pom.xml

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.19</version>
    <scope>compile</scope>
</dependency>

然后这样做:

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

Client client = new Client();
final WebResource r = client.resource("http://localhost:9200").path("/myindex/_search");
String requestJson = "{\"query\" : {\"match\" : {\"type\" : \"book\"} }}";
ClientResponse response = r.post(ClientResponse.class, requestJson);
String json = response.getEntity(String.class);

Gson gson = new GsonBuilder().setPrettyPrinting()
        .create();
Map map = gson.fromJson(json, Map.class);
System.out.println(gson.toJson(map));

// to convert to SearchResponse:
JsonXContentParser xContentParser = new JsonXContentParser(NamedXContentRegistry.EMPTY,
            new JsonFactory().createParser(json));
SearchResponse searchResponse = SearchResponse.fromXContent(xContentParser);

示例输出:

{
    "took": 9.0,
    "timed_out": false,
    "_shards": {
        "total": 5.0,
        "successful": 5.0,
        "failed": 0.0
    },
    "hits": {
        "total": 1.0,
        "max_score": 0.2876821,
        "hits": [
        {
            "_index": "myindex",
            "_type": "mydoc",
            "_id": "AWXp8gZjXyu6lA_2Kpi2",
            "_score": 0.2876821,
            "_source": {
                "title": "foobar",
                "type": "book"
            }
        }
        ]
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.