preface

This article is a simple implementation of Java API, but only simple implementation, does not consider including parameter verification, exception handling, log handling, security, etc., for reference only

See UsefullESSearchSkill for the code, please refer to the original query statement

Runtime environment

JDK version: 10.0.2 Gradle version: 4.7 Elasticsearch version: 6.3.2 IDEA version: 2018.2

Before running, start the ES instance and modify the ES configuration in the application.properties file

Classes introduce

The entity class Book

Note: The date publish_date type is set to String to avoid complicated conversion work between Java and ES, where the field is still recognized as date

public class Book {
    public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); private String id; private String title; private List<String> authors; private String summary; private String publish_date; private Integer num_reviews; private String publisher; . }Copy the code

Public class Constants

Defines some commonly used constants

Public class Constants {// Field name public static String ID ="id";
    public static String TITLE = "title";
    public static String AUTHORS = "authors";
    public static String SUMMARY = "summary";
    public static String PUBLISHDATE = "publish_date";
    public static String PUBLISHER = "publisher";
    public static String NUM_REVIEWS = "num_reviews";

    public static String TITLE_KEYWORD = "title.keyword";
    public static String PUBLISHER_KEYWORD = "publisher.keyword"; Public static String[] fetchFieldsTSPD = {ID, TITLE, SUMMARY, PUBLISHDATE}; public static String[] fetchFieldsTA = {ID, TITLE, AUTHORS}; public static String[] fetchFieldsSA = {ID, SUMMARY, AUTHORS}; public static String[] fetchFieldsTSA = {ID, TITLE, SUMMARY, AUTHORS}; public static String[] fetchFieldsTPPD = {ID, TITLE, PUBLISHER, PUBLISHDATE}; public static String[] fetchFieldsTSPN = {ID, TITLE, SUMMARY, PUBLISHER, NUM_REVIEWS}; Public static HighlightBuilder highlightS = new HighlightBuilder().field(SUMMARY); }Copy the code

Public class EsConfig

Create an ES client instance that interacts with the ES cluster

@Configuration
public class EsConfig {

    @Value("${elasticsearch.cluster-nodes}")
    private String clusterNodes;

    @Value("${elasticsearch.cluster-name}")
    private String clusterName;

    @Bean
    public Client client() {
        Settings settings = Settings.builder().put("cluster.name", clusterName)
                .put("client.transport.sniff".true).build();

        TransportClient client = new PreBuiltTransportClient(settings);
        try {
            if(clusterNodes ! = null && !"".equals(clusterNodes)) {
                for (String node : clusterNodes.split(",")) {
                    String[] nodeInfo = node.split(":");
                    client.addTransportAddress(new TransportAddress(InetAddress.getByName(nodeInfo[0]), Integer.parseInt(nodeInfo[1])));
                }
            }
        } catch (UnknownHostException e) {
        }

        returnclient; }}Copy the code

The data acquisition utility class DataUtil

The data here are the four data used in the experiment of the 23 most useful ES retrieval techniques

public class DataUtil {

    public static SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd"); Public static List<Book>batchData() {
        List<Book> list = new LinkedList<>();
        Book book1 = new Book("1"."Elasticsearch: The Definitive Guide", Arrays.asList("clinton gormley"."zachary tong"),
                "A distibuted real-time search and analytics engine"."2015-02-07", 20, "oreilly");
        Book book2 = new Book("2"."Taming Text: How to Find, Organize, and Manipulate It", Arrays.asList("grant ingersoll"."thomas morton"."drew farris"),
                "organize text using approaches such as full-text search, proper name recognition, clustering, tagging, information extraction, and summarization"."2013-01-24", 12, "manning");
        Book book3 = new Book("3"."Elasticsearch in Action", Arrays.asList("radu gheorge"."matthew lee hinman"."roy russo"),
                "build scalable search applications using Elasticsearch without having to do complex low-level programming or understand  advanced data science algorithms"."2015-12-03", 18."manning");
        Book book4 = new Book("4"."Solr in Action", Arrays.asList("trey grainger"."timothy potter"), "Comprehensive guide to implementing a scalable search engine using Apache Solr"."2014-04-05", 23, "manning");

        list.add(book1);
        list.add(book2);
        list.add(book3);
        list.add(book4);

        return list;
    }

    public static Date parseDate(String dateStr) {
        try {
            return dateFormater.parse(dateStr);
        } catch (ParseException e) {
        }
        return null;
    }

Copy the code

Common query utility class CommonQueryUtils

Parse the data after executing the ES query request

public class CommonQueryUtils {

    public static Gson gson = new GsonBuilder().setDateFormat("YYYY-MM-dd").create(); /** * process the data returned by ES, Public static List<Book> parseResponse(SearchResponse SearchResponse) {List<Book> List = new LinkedList<>();for(SearchHit hit : Searchresponse.gethits ().gethits ()) {Book Book = gson.fromjson (hit.getSourceasString (), book.class); list.add(book); }returnlist; } /** * After parsing the data, Public static Response<List<Book>> buildResponse(SearchResponse SearchResponse) {// Timeout handlingif (searchResponse.isTimedOut()) {
            returnnew Response<>(ResponseCode.ESTIMEOUT); List<Book> List = parseResponse(searchResponse); // Shard execution failedif (searchResponse.getFailedShards() > 0) {
            return new Response<>(ResponseCode.FAILEDSHARDS, list);
        }
        returnnew Response<>(ResponseCode.OK, list); }... }Copy the code

Data preparation

BulkTests

Create indexes and use the BULK API to bulk insert data

@runwith (springrunner.class) @springbooTtest Public class BulkTests {// In Test Autowired needs to import packages Org. Elasticsearch. Plugin: transport - netty4 - client: 6.3.2, or abnormal find transport class @autowired private client client; @Value("${elasticsearch.bookIndex}")
    private String bookIndex;

    @Value("${elasticsearch.bookType}")
    private String bookType;

    private Gson gson = new GsonBuilder().setDateFormat("YYYY-MM-dd").create(); /** * create an index, set Settings, set mappings */ @test public voidcreateIndex() { int settingShards = 1; int settingReplicas = 0; IndicesExistsResponse = client.admin().indicesExistsResponse ().prepareExists(bookIndex).get();if (indicesExistsResponse.isExists()) {
            System.out.println("Index" + bookIndex + "There is!); // Drop index, To prevent the abnormal ResourceAlreadyExistsException [index bookdb_index/yL05ZfXFQ4GjgOEM5x8tFQ already exists DeleteIndexResponse deleteResponse = client.admin().indices().prepareDelete(bookIndex).get();if (deleteResponse.isAcknowledged()){
                System.out.println("Index" + bookIndex + "Deleted");
            }else {
                System.out.println("Index" + bookIndex + "Delete failed"); }}else {
            System.out.println("Index" + bookIndex + "It doesn't exist!); } // Set Settings CreateIndexResponse Response = client.admin().indices().prepaset (bookIndex) .setSettings(Settings.builder() .put("index.number_of_shards", settingShards)
                        .put("index.number_of_replicas", settingReplicas)) .get(); GetSettingsResponse GetSettingsResponse = client.admin().indices().prepareGetSettings(bookIndex).get(); System.out.println("Index setting result");
        for (ObjectObjectCursor<String, Settings> cursor : getSettingsResponse.getIndexToSettings()) {
            String index = cursor.key;
            Settings settings = cursor.value;
            Integer shards = settings.getAsInt("index.number_of_shards", null);
            Integer replicas = settings.getAsInt("index.number_of_replicas", null);
            System.out.println("index:" + index + ", shards:" + shards + ", replicas:" + replicas);

            Assert.assertEquals(java.util.Optional.of(settingShards), java.util.Optional.of(shards));
            Assert.assertEquals(java.util.Optional.of(settingReplicas), java.util.Optional.of(replicas));
        }
    }

    /**
     * Bulk 批量插入数据
     */
    @Test
    public void bulk() { List<Book> list = DateUtil.batchData(); BulkRequestBuilder bulkRequestBuilder = client.prepareBulk(); ForEach (book -> {// this API is used in a new versionsetWhen Source, the number of arguments must be even, otherwise addsetSource(json, XContentType.JSON)
            bulkRequestBuilder.add(client.prepareIndex(bookIndex, bookType, book.getId()).setSource(gson.toJson(book), XContentType.JSON));
        });

        BulkResponse responses = bulkRequestBuilder.get();
        if(responses. HasFailures ()) {// Bulk failedfor (BulkItemResponse res : responses) {
                System.out.println(res.getFailure());
            }
            Assert.assertTrue(false); }}}Copy the code

Began to query

The control class

Query interface

@RestController
@RequestMapping("basicmatch") public class BasicMatchQueryController { @Autowired private BasicMatchQueryService basicMatchQueryService; / * * * to 1.1"guide"Full-text retrieval * test: http://localhost:8080/basicmatch/multimatch? query=guide */ @RequestMapping("multimatch")
    public Response<List<Book>> multiMatch(@RequestParam(value = "query", required = true) String query) {
        returnbasicMatchQueryService.multiBatch(query); } / * * * * 1.2 specifies a specific field retrieval test: http://localhost:8080/basicmatch/match? title=in action&from=0&size=4
     */
    @RequestMapping("match")
    public ResponsePage<List<Book>> match(MatchForm form) {
        returnbasicMatchQueryService.match(form); } /** * 2 yes"guide"Perform many fields retrieve * test: http://localhost:8080/basicmatch/multifield? query=guide */ @RequestMapping("multifield")
    public Response<List<Book>> multiField(@RequestParam(value = "query", required = true) String query) {
        returnbasicMatchQueryService.multiField(query); } / * * * 3, Boosting a field score increased retrieval (Boosting) : the score of "abstract" field by * 3 times test: http://localhost:8080/basicmatch/multifieldboost? query=elasticsearch guide */ @RequestMapping("multifieldboost")
    public Response<List<Book>> multiFieldboost(@RequestParam(value = "query", required = true) String query) {
        returnbasicMatchQueryService.multiFieldboost(query); } / * * * 4, Boolean retrieval (Boolean Query) * test: http://localhost:8080/basicmatch/bool? shouldTitles=Elasticsearch&shouldTitles=Solr&mustAuthors=clinton gormely&mustNotAuthors=radu gheorge */ @RequestMapping("bool")
    public Response<List<Book>> bool(@ModelAttribute BoolForm form) {
        returnbasicMatchQueryService.bool(form); } / * * * 5, Fuzzy Fuzzy retrieval (Fuzzy Queries) * / @ RequestMapping ("fuzzy")
    public Response<List<Book>> fuzzy(String query) {
        returnbasicMatchQueryService.fuzzy(query); } / 6 * * *, the Wildcard Query Wildcard searching * test: http://localhost:8080/basicmatch/wildcard? pattern=t* */ @RequestMapping("wildcard")
    public Response<List<Book>> wildcard(String pattern) {
        returnbasicMatchQueryService.wildcard(Constants.AUTHORS, pattern); } / * * * 7, regular expression retrieval (Regexp Query) test: * * / @ RequestMapping (http://localhost:8080/basicmatch/regexp"regexp"Public Response<List<Book>> regexp(String regexp) {public Response<List<Book>> regexp(String regexp)"t[a-z]*y";
        returnbasicMatchQueryService.regexp(Constants.AUTHORS, regexp); } / * * * 8, matching Phrase retrieval (Match Phrase Query) * test: http://localhost:8080/basicmatch/phrase? query=search engine */ @RequestMapping("phrase")
    public Response<List<Book>> phrase(String query) {
        returnbasicMatchQueryService.phrase(query); } / * * * * 9, the phrase prefix matching retrieval test: http://localhost:8080/basicmatch/phraseprefix? query=search en */ @RequestMapping("phraseprefix")
    public Response<List<Book>> phrasePrefix(String query) {
        returnbasicMatchQueryService.phrasePrefix(query); } / * * * 10, String retrieval (Query String) * test: http://localhost:8080/basicmatch/querystring? query=(saerch~1 algorithm~1) AND (grant ingersoll) OR (tom morton) */ @RequestMapping("querystring")
    public Response<List<Book>> queryString(String query) {
        returnbasicMatchQueryService.queryString(query); } / * * * 11, simplified String retrieval (Simple Query String) * test: http://localhost:8080/basicmatch/simplequerystring? query=(saerch~1 algorithm~1) AND (grant ingersoll) OR (tom morton) */ @RequestMapping("simplequerystring") public Response<List<Book>> simpleQueryString (String query) {//"(saerch~1 algorithm~1) + (grant ingersoll) | (tom morton)";
        returnbasicMatchQueryService.simpleQueryString(query); } / * * * 12, Term (specified field retrieval) * = retrieval test: http://localhost:8080/basicmatch/term? query=manning */ @RequestMapping("term")
    public Response<List<Book>> term(String query) {
        returnbasicMatchQueryService.term(query); } / * * * 13, Term retrieval - (Term Query - Sorted) * test: http://localhost:8080/basicmatch/termsort? query=manning */ @RequestMapping("termsort")
    public Response<List<Book>> termsort(String query) {
        returnbasicMatchQueryService.termsort(query); * * *} / 14, scope, retrieval (Range query) * test: http://localhost:8080/basicmatch/range? startDate=2015-01-01&endDate=2015-12-31 */ @RequestMapping("range")
    public Response<List<Book>> range(String startDate, String endDate) {
        returnbasicMatchQueryService.range(startDate, endDate); } / 15. * * * * filter retrieval testing: http://localhost:8080/basicmatch/filter? query=elasticsearch&gte=20 */ @RequestMapping("filter")
    public Response<List<Book>> filter(String query, Integer gte, Integer lte) {
        returnbasicMatchQueryService.filter(query, gte, lte); } /** * 17, Function Score: The Field Value Factor) * testing: http://localhost:8080/basicmatch/fieldvaluefactor? query=search engine */ @RequestMapping("fieldvaluefactor")
    public Response<List<Book>> fieldValueFactor(String query) {
        returnbasicMatchQueryService.fieldValueFactor(query); } / * * * 18, the Function Score: attenuation Function (Function Score: Decay Functions provides) * test: http://localhost:8080/basicmatch/decay? query=search engines&origin=2014-06-15 */ @RequestMapping("decay")
    public Response<List<Book>> decay(String query, @RequestParam(value = "origin", defaultValue = "2014-06-15") String origin) {
        returnbasicMatchQueryService.decay(query, origin); } /** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **"script")
    public Response<List<Book>> script(String query, @RequestParam(value = "threshold", defaultValue = "2015-07-30") String threshold) {
        returnbasicMatchQueryService.script(query, threshold); }}Copy the code

Service class

@Service
public class BasicMatchQueryService {
    @Autowired
    private Client client;

    @Value("${elasticsearch.bookIndex}")
    private String bookIndex;

    @Value("${elasticsearch.bookType}") private String bookType; /** * Private SearchResponse requestGet(String queryName, SearchRequestBuilder requestBuilder) { System.out.println(queryName +"Built query:" + requestBuilder.toString());
        SearchResponse searchResponse = requestBuilder.get();
        System.out.println(queryName + "Search Results: + searchResponse.toString());
        returnsearchResponse; }... }Copy the code

1.1 Perform full-text search on “Guide” Multi Match Query

    public Response<List<Book>> multiBatch(String query) {
        MultiMatchQueryBuilder queryBuilder = new MultiMatchQueryBuilder(query);

        SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex)
                .setTypes(bookType).setQuery(queryBuilder);

        SearchResponse searchResponse = requestGet("multiBatch", requestBuilder);

        return CommonQueryUtils.buildResponse(searchResponse);
    }
Copy the code

1.2 Search for books with “in Action “in the title field

    public ResponsePage<List<Book>> match(MatchForm form) {
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("title", form.getTitle()); HighlightBuilder HighlightBuilder = new HighlightBuilder().field()"title").fragmentSize(200); SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex) .setTypes(bookType).setQuery(matchQueryBuilder) .setFrom(form.getFrom()).setSize(form.getSize()).highlighter(highlightBuilder) // Sets the field to return by _source .setFetchSource(Constants.fetchFieldsTSPD, null); . }Copy the code

Multi-field Search

    public Response<List<Book>> multiField(String query) {
        MultiMatchQueryBuilder queryBuilder = new MultiMatchQueryBuilder(query).field("title").field("summary"); SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex) .setTypes(bookType).setQuery(queryBuilder); . }Copy the code

Boosting the retrieval of a field score, Boosting the score of the “Abstract” field by 3 times

    public Response<List<Book>> multiFieldboost(String query) {
        MultiMatchQueryBuilder queryBuilder = new MultiMatchQueryBuilder(query).field("title").field("summary", 3); SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex) .setTypes(bookType).setQuery(queryBuilder); . }Copy the code

4, Bool Query (Bool Query)

/** * Search in the title for a book named"Elasticsearch""Solr"The book, * AND by"clinton gormley"Created, but NOT by"radu gheorge"Create */ public Response<List<Book>> bool(BoolForm form) {BoolQueryBuilder boolQuery = new BoolQueryBuilder(); // Should BoolQueryBuilder shouldTitleBool = new BoolQueryBuilder(); form.getShouldTitles().forEach(title -> { shouldTitleBool.should().add(new MatchQueryBuilder("title", title)); }); boolQuery.must().add(shouldTitleBool); // Match author form.getMustauthors ().foreach (author -> {boolQuery.must().add(new MatchQueryBuilder())"authors", author)); }); // Not match author form.getMustNotauthors ().foreach (author -> {boolQuery.mustnot ().add(new MatchQueryBuilder())"authors", author)); }); . }Copy the code

5, Fuzzy Fuzzy Queries

    public Response<List<Book>> fuzzy(String query) {
        MultiMatchQueryBuilder queryBuilder = new MultiMatchQueryBuilder(query)
                .field("title").field("summary") .fuzziness(Fuzziness.AUTO); SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex) .setTypes(bookType).setQuery(queryBuilder) .setFetchSource(Constants.fetchFieldsTSPD, null) .setSize(2); . }Copy the code

6. Wildcard Query Wildcard Query

/** ** to find with a"t"Public Response<List<Book>> Wildcard (String fieldName, String pattern) { WildcardQueryBuilder wildcardQueryBuilder = new WildcardQueryBuilder(fieldName, pattern); HighlightBuilder highlightBuilder = new HighlightBuilder().field(Constants.AUTHORS, 200); SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex) .setTypes(bookType).setQuery(wildcardQueryBuilder)  .setFetchSource(Constants.fetchFieldsTA, null) .highlighter(highlightBuilder); }Copy the code

7. Regular expression Query (Regexp Query)

public Response<List<Book>> regexp(String fieldName, String regexp) { RegexpQueryBuilder queryBuilder = new RegexpQueryBuilder(fieldName, regexp); HighlightBuilder highlightBuilder = new HighlightBuilder().field(Constants.AUTHORS); SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex) .setQuery(queryBuilder).setTypes(bookType).highlighter(highlightBuilder) .setFetchSource(Constants.fetchFieldsTA, null);  }Copy the code

8. Match Phrase Query

    public Response<List<Book>> phrase(String query) {
        MultiMatchQueryBuilder queryBuilder = new MultiMatchQueryBuilder(query)
                .field(Constants.TITLE).field(Constants.SUMMARY)
                .type(MultiMatchQueryBuilder.Type.PHRASE).slop(3);

        SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex).setTypes(bookType)
                .setQuery(queryBuilder)
                .setFetchSource(Constants.fetchFieldsTSPD, null);
    }
Copy the code

9, matching phrase prefix retrieval

    public Response<List<Book>> phrasePrefix(String query) {
        MatchPhrasePrefixQueryBuilder queryBuilder = new MatchPhrasePrefixQueryBuilder(Constants.SUMMARY, query)
                .slop(3).maxExpansions(10);

        SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex).setTypes(bookType)
                .setQuery(queryBuilder).setFetchSource(Constants.fetchFieldsTSPD, null);
    }
Copy the code

10. Query String

    public Response<List<Book>> queryString(String query) {
        QueryStringQueryBuilder queryBuilder = new QueryStringQueryBuilder(query);
        queryBuilder.field(Constants.SUMMARY, 2).field(Constants.TITLE)
                .field(Constants.AUTHORS).field(Constants.PUBLISHER);

        SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex).setTypes(bookType)
                .setQuery(queryBuilder).setFetchSource(Constants.fetchFieldsTSA, null);
    }
Copy the code

11. Simple Query String

    public Response<List<Book>> simpleQueryString(String query) {
        SimpleQueryStringBuilder queryBuilder = new SimpleQueryStringBuilder(query);
        queryBuilder.field(Constants.SUMMARY, 2).field(Constants.TITLE)
                .field(Constants.AUTHORS).field(Constants.PUBLISHER);

        SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex).setTypes(bookType)
                .setQuery(queryBuilder).setFetchSource(Constants.fetchFieldsTSA, null)
                .highlighter(Constants.highlightS);
    }
Copy the code

12, Term/Terms search (specified field search)

public Response<List<Book>> term(String query) { TermQueryBuilder termQueryBuilder = new TermQueryBuilder(Constants.PUBLISHER, query); // terms query /*String[] values = {"manning"."oreilly"}; TermsQueryBuilder termsQueryBuilder = new TermsQueryBuilder(Constants.PUBLISHER, values); */ SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex).setTypes(bookType) .setQuery(termQueryBuilder) .setFetchSource(Constants.fetchFieldsTPPD, null); }Copy the code

13, Sorted by Term Query – (Term Query – Sorted)

    public Response<List<Book>> termsort(String query) {
        TermQueryBuilder termQueryBuilder = new TermQueryBuilder(Constants.PUBLISHER, query);

        SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex).setTypes(bookType)
                .setQuery(termQueryBuilder)
                .addSort(Constants.PUBLISHER_KEYWORD, SortOrder.DESC)
                .addSort(Constants.TITLE_KEYWORD, SortOrder.ASC)
                .setFetchSource(Constants.fetchFieldsTPPD, null);
    }
Copy the code

14. Range Query

    public Response<List<Book>> range(String startDate, String endDate) {
        RangeQueryBuilder queryBuilder = new RangeQueryBuilder(Constants.PUBLISHDATE)
                .gte(startDate).lte(endDate);

        SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex).setTypes(bookType)
                .setQuery(queryBuilder)
                .setFetchSource(Constants.fetchFieldsTPPD, null);
    }
Copy the code

15. Filter search

    public Response<List<Book>> filter(String query, Integer gte, Integer lte) {
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        queryBuilder.must().add(new MultiMatchQueryBuilder(query).field(Constants.TITLE).field(Constants.SUMMARY));
        if(gte ! = null || lte ! = null) { RangeQueryBuilder rangeQueryBuilder = new RangeQueryBuilder(Constants.NUM_REVIEWS);if(gte ! = null) { rangeQueryBuilder.gte(gte); }if(lte ! = null) { rangeQueryBuilder.lte(lte); } queryBuilder.filter().add(rangeQueryBuilder); } SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex).setTypes(bookType) .setQuery(queryBuilder).setFetchSource(Constants.fetchFieldsTSPN, null); }Copy the code

17, Function Score: Field Value Factor

    public Response<List<Book>> fieldValueFactor(String query) {
        // query
        MultiMatchQueryBuilder multiMatchQueryBuilder = new MultiMatchQueryBuilder(query)
                .field(Constants.TITLE).field(Constants.SUMMARY);
        // fieldValueFactor
        FieldValueFactorFunctionBuilder fieldValueFactor = ScoreFunctionBuilders.fieldValueFactorFunction(Constants.NUM_REVIEWS)
                .factor(2).modifier(FieldValueFactorFunction.Modifier.LOG1P);
        // functionscore
        FunctionScoreQueryBuilder queryBuilder = QueryBuilders.functionScoreQuery(multiMatchQueryBuilder, fieldValueFactor);

        SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex).setTypes(bookType)
                .setQuery(queryBuilder).setFetchSource(Constants.fetchFieldsTSPN, null);
    }
Copy the code

16, Function Score: Decay Functions

    public Response<List<Book>> decay(String query, String origin) {
        MultiMatchQueryBuilder multiMatchQueryBuilder = new MultiMatchQueryBuilder(query)
                .field(Constants.TITLE).field(Constants.SUMMARY);
        ExponentialDecayFunctionBuilder exp = ScoreFunctionBuilders.exponentialDecayFunction(Constants.PUBLISHDATE, origin, "30d"."7d");

        FunctionScoreQueryBuilder queryBuilder = QueryBuilders.functionScoreQuery(multiMatchQueryBuilder, exp).boostMode(CombineFunction.REPLACE);

        SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex).setTypes(bookType)
                .setQuery(queryBuilder).setFetchSource(Constants.fetchFieldsTSPN, null);
    }
Copy the code

19, Function Score: Script Scoring

public Response<List<Book>> script(String query, String threshold) { MultiMatchQueryBuilder multiMatchQueryBuilder = new MultiMatchQueryBuilder(query) .field(Constants.TITLE).field(Constants.SUMMARY); // Map<String, Object> params = new HashMap<>(); params.put("threshold", threshold); // script String scriptStr ="publish_date = doc['publish_date'].value; num_reviews = doc['num_reviews'].value; Parse (' YYYY-MM-dd ', threshold).gettime ()) {return log(2.5 + num_reviews)}; publish_date > date.parse (' YYYY-MM-dd ', threshold).gettime ()) {return log(2.5 + num_reviews)}; return log(1 + num_reviews);";
        Script script = new Script(ScriptType.INLINE, "painless", scriptStr, params);

        ScriptScoreFunctionBuilder scriptScoreFunctionBuilder = ScoreFunctionBuilders.scriptFunction(script);

        FunctionScoreQueryBuilder queryBuilder = QueryBuilders.functionScoreQuery(multiMatchQueryBuilder, scriptScoreFunctionBuilder);

        SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex).setTypes(bookType)
                .setQuery(queryBuilder).setFetchSource(Constants.fetchFieldsTSPN, null);
    }
Copy the code

For more, visit my personal blog at laijianfeng.org/

Open the wechat scan, follow the wechat official account of “Xiao Xiao Xiao Feng”, and timely receive the blog push