1. 程式人生 > >elasticsearch 2.4.4 search template javaapi

elasticsearch 2.4.4 search template javaapi

Define your template parameters as a Map<String,Object>:

Map<String, Object> template_params = new HashMap<>();
template_params.put("param_gender", "male");

You can use your stored search templates in config/scripts. For example, if you have a file named config/scripts/template_gender.mustache

 containing:

{
    "template" : {
        "query" : {
            "match" : {
                "gender" : "{{param_gender}}"
            }
        }
    }
}

Execute it with:

SearchResponse sr = client.prepareSearch()
        .setTemplateName("template_gender")
        .setTemplateType(ScriptService.ScriptType.FILE)
        .setTemplateParams(template_params)
        .get();

You can also store your template in a special index named .scripts:

client.preparePutIndexedScript("mustache", "template_gender",
        "{\n" +
        "    \"template\" : {\n" +
        "        \"query\" : {\n" +
        "            \"match\" : {\n" +
        "                \"gender\" : \"{{param_gender}}\"\n" +
        "            }\n" +
        "        }\n" +
        "    }\n" +
        "}").get();

To execute an indexed templates, use ScriptService.ScriptType.INDEXED:

SearchResponse sr = client.prepareSearch()
        .setTemplateName("template_gender")
        .setTemplateType(ScriptService.ScriptType.INDEXED)
        .setTemplateParams(template_params)
        .get();

例項:

pom.xml 

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">     <modelVersion>4.0.0</modelVersion>

    <groupId>com.smoner.study</groupId>     <artifactId>elasticsearch</artifactId>     <version>1.0-SNAPSHOT</version> <dependencies>     <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->     <dependency>         <groupId>org.elasticsearch</groupId>         <artifactId>elasticsearch</artifactId>         <version>2.4.4</version>     </dependency>     <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->     <dependency>         <groupId>org.elasticsearch.client</groupId>         <artifactId>transport</artifactId>         <version>5.0.0</version>     </dependency>

    <!--<dependency>-->         <!--<groupId>org.elasticsearch.client</groupId>-->         <!--<artifactId>transport</artifactId>-->         <!--<version>2.4.0</version>-->     <!--</dependency>-->

    <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-elasticsearch -->     <dependency>         <groupId>org.springframework.data</groupId>         <artifactId>spring-data-elasticsearch</artifactId>         <version>2.1.0.RELEASE</version>     </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->     <dependency>         <groupId>org.apache.logging.log4j</groupId>         <artifactId>log4j-api</artifactId>         <version>2.11.0</version>     </dependency>

    <dependency>         <groupId>org.apache.logging.log4j</groupId>         <artifactId>log4j-core</artifactId>         <version>2.9.1</version>     </dependency>

    <dependency>         <groupId>com.fasterxml.jackson.core</groupId>         <artifactId>jackson-databind</artifactId>         <version>2.1.3</version>     </dependency> </dependencies>     <build>         <plugins>             <plugin>                 <artifactId>maven-compiler-plugin</artifactId>                 <version>3.7.0</version>                 <configuration>                     <source>1.8</source>                     <target>1.8</target>                     <encoding>UTF-8</encoding>                 </configuration>             </plugin>             <plugin>                 <groupId>org.apache.maven.plugins</groupId>                 <artifactId>maven-shade-plugin</artifactId>                 <version>2.4.1</version>                 <executions>                     <execution>                         <phase>package</phase>                         <goals>                             <goal>shade</goal>                         </goals>                         <configuration>                             <transformers>                                 <transformer                                         implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />                             </transformers>                         </configuration>                     </execution>                 </executions>             </plugin>

        </plugins>     </build> </project>

java 程式碼:

package com.smoner.study.template;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.SearchHit;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by smoner on 2018/9/29.
 */
public class EsTempService {
    TransportClient transportClient = null;
    public static void main(String[] args) throws Exception{
        try{
            EsTempService esTempService = new EsTempService();
//            esTempService.initData();
            esTempService.templateInit();
//            esTempService.queryTest();
        }catch (Exception e){
            e.printStackTrace();
            String d = null;
        }
    }

    public void queryTest() throws Exception{
        TransportClient transportClient = this.getTransport();
        SearchResponse searchresponse =
        transportClient.prepareSearch("biprice").setTypes("his").setQuery(
                QueryBuilders.matchAllQuery()
        ).get();
        System.out.println("-->>>>>>>>-----------------------");
        if(searchresponse.getHits().getHits().length>0){
            for(SearchHit searchHit:searchresponse.getHits().getHits()){
                System.out.println(searchHit.getSourceAsString());
            }
        }
    }

    public void closeTransport(){
        if(transportClient!=null){
            transportClient.close();
        }
    }
    public TransportClient getTransport()throws Exception{
        if(null!=transportClient){
            return transportClient ;
        }
        Settings settings = Settings.builder().put("cluster.name","elasticsearch")
                .put("client.transport.sniff",true)
                .build();
        transportClient = TransportClient.builder().settings(settings).build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"),9300));
        return transportClient;
    }

    public void initData()throws Exception{
        TransportClient transportClient = this.getTransport();
        for (int i = 0;i<5;i++) {
            transportClient.prepareIndex("biprice","his").setSource(
                    XContentFactory.jsonBuilder().startObject()
                            .field("tenantid","tenantid"+i)
                            .field("enterpriseid",100+i)
                            .field("nprice",100+i)
                            .field("nnum",20+i)
                            .field("vunit","個")
                            .field("vsupplyname","青島公司"+i)
                            .endObject()
            ).get();
        }
    }
    public void templateInit() throws Exception{
        TransportClient transportClient = this.getTransport();
        String templateScript = "{\n" +  " \"query\" : {\n" +  "   \"match\" : {\n" +  "  \"tenantid\" : \"{{tenantid}}\"\n" +  "   }\n" +   "   }\n" +    "}";;
        Map<String,Object> map = new HashMap<>();
        map.put("tenantid","tenantid1");

        transportClient.preparePutIndexedScript("mustache","ycprice_tmp1",templateScript).get();

        SearchResponse sr = transportClient.prepareSearch()
                .setTemplateName("ycprice_tmp1")
                .setTemplateType(ScriptService.ScriptType.INDEXED)
                .setTemplateParams(map)
                .get();
        System.out.println("----------------------->>>>>>>>");
        if(sr.getHits().getHits().length>0){
            for(SearchHit searchHit:sr.getHits().getHits()){
                System.out.println(searchHit.getSourceAsString());
            }
        }
    }
}