“This is the 12th day of my participation in the Gwen Challenge in November. See details of the event: The Last Gwen Challenge 2021”.

Recently using ES to do search services, anyway is a novice, all kinds of attempts.

The initial release

I went straight to the Internet. I just wrote a simple business. Search. The code is as follows

SearchRequest searchRequest = new SearchRequest(); Searchrequest. indices("general_content"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.from((param.getPageIndex() - 1) * param.getPageSize()); searchSourceBuilder.size(param.getPageSize()); String searchKey = param.getSearchKey(); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery() .must(QueryBuilders.termQuery("platformId", param.getPlatformId())) .must(QueryBuilders.termQuery("typeCode", param.getTypeCode())) .must(QueryBuilders.termQuery("projectCode", param.getProjectCode())) .must(QueryBuilders.termQuery("publish", "1")); if (StringUtils.hasLength(searchKey)) { boolQueryBuilder.must(QueryBuilders.multiMatchQuery(searchKey, new String[]{"title", "summary"}).operator(Operator.AND)); } searchSourceBuilder.query(boolQueryBuilder) .sort(SortBuilders.fieldSort("top").order(SortOrder.DESC)) .sort(SortBuilders.fieldSort("sort").order(SortOrder.DESC)) .sort(SortBuilders.fieldSort("createdTime").order(SortOrder.DESC)); searchRequest.source(searchSourceBuilder); List<GeneralContentPO> list = new ArrayList<>(); long totalHits; try { SearchResponse searchResponse; searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); totalHits = searchResponse.getHits().getTotalHits().value; if (totalHits > 0) { SearchHit[] searchHit = searchResponse.getHits().getHits(); for (SearchHit hit : searchHit) { Map<String, Object> map = hit.getSourceAsMap(); list.add(objectMapper.convertValue(map, GeneralContentPO.class)); }}} catch (Exception e) {log.error(" error: {}", e); throw new SearchException(SearchResultEnum.SEARCH_ERROR); }Copy the code

So let me write it out. We tested it and it’s fine. Heart that is a happy

Discover a new continent

Doing search service kept looking at this Elastic-search-in-action.medcl.com/ and saw a noun enter my eyes. search template

So I gave it a try

Building a search template

POST _scripts/content_search_template_v1
{
  "script": {
    "lang": "mustache",
    "source": {
      "from": "{{from}}",
      "size": "{{size}}",
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "platformId": {
                  "value": "{{platformId}}",
                  "boost": 1
                }
              }
            },
            {
              "term": {
                "typeCode": {
                  "value": "{{typeCode}}",
                  "boost": 1
                }
              }
            },
            {
              "term": {
                "projectCode": {
                  "value": "{{projectCode}}",
                  "boost": 1
                }
              }
            },
            {
              "term": {
                "publish": {
                  "value": "{{publish}}",
                  "boost": 1
                }
              }
            },
            {
              "multi_match": {
                "query": "{{query}}",
                "fields": [
                  "summary",
                  "title"
                ],
                "boost": 1
              }
            }
          ]
        }
      },
      "sort": [
        {
          "top": {
            "order": "desc"
          }
        },
        {
          "sort": {
            "order": "desc"
          }
        },
        {
          "publish": {
            "order": "desc"
          }
        },
        {
          "createdTime": {
            "order": "desc"
          }
        }
      ]
    }
  }
}

Copy the code

call

GET general_content/_search/template
{
  "id": "content_search_template_v1",
  "params": {
    "platformId": "xxx",
    "typeCode":"xxx",
    "projectCode":"xxx",
    "publish":"xxx",
    "query": "xxx",
    "size": 10,
    "from": 0
  }
}
Copy the code

Alas large large. You can. Can completely

So you don’t need a bunch of code. Completely lightened the code

The benefits of using template

  • Avoid repeating code in multiple places
  • Easier to test and execute your queries
  • Share queries between applications
  • Allows users to execute only a few predefined queries
  • Separate search logic from application logic

The problem

I found another problem. I fit if the field is null. What if you don’t search for this field?

And found this article: elasticstack.blog.csdn.net/article/det…

In Mustache, there’s no if/else, but you can have sections to skip it if the variable is false or not defined:

{{#param1}}
    "This section is skipped if param1 is null or false"
{{/param1}}
Copy the code

Specific can see the article that says above. I’m not showing it here

conclusion

Using the Search template is really good. The search template can be modified. Later only need to dynamically configure the template name is good. Simple and convenient.

One for the newbie. Have fun.