当前位置:   article > 正文

ES模糊查询(任意位置模糊)_es针对字段是一个对象的模糊查询

es针对字段是一个对象的模糊查询

编写目的

总结一下实际项目开发中遇到的问题以及解决方法,也供其他伙伴们查看,交流。如果希望部署在云服务器上的话,可以参考 大学生选择云服务器,腾讯云?阿里云?还是华为云? 选择产商购买,参考 elastic search 集群教程(Elastic Search 7) 进行安装,集群搭建等。

具体过程

elastic search7 java开发简单教程 中提到四种模糊查询,并且编写了prefix例子(即模糊字段在后面),但是实际情况可能包括其他位置模糊的情况,今天正要遇到了这个需求,项目经理让我根据某个excel表,根据里面的字段,把所有以这些字段结尾的图片的url拿出来,给做算法的训练模型。
也就是说,已知某个字段最后四个字母,获得所有以这些字符结尾的数据。

基本思路: query.

/**
 *  根据key和这个key的结尾字符串查询
 * @param key
 * @param tail
 * @return
 */
public static List<String> seachTail( final String key, final String tail) {
	// 其中ES_NAME是指索引,也可以理解为数据库名
    SearchTemplateRequest request = new SearchTemplateRequest();
    request.setRequest(new SearchRequest(ES_NAME));

    request.setScriptType(ScriptType.INLINE);
    request.setScript("{\n" +
            "    \"query\": {\n" +
            "        \"wildcard\": {\n" +
            "            \""+key+"\": {\n" +
            "                \"value\": \"*"+tail+"\"\n" +
            "            }\n" +
            "        }\n" +
            "    }\n" +
            "}\n");

    Map<String, Object> scriptParams = new HashMap<>();
    request.setScriptParams(scriptParams);
    RestHighLevelClient client = getRestHighLevelClient();
    SearchTemplateResponse searchTemplateResponse = null;
    // 拼凑好了后,执行
    try {
        searchTemplateResponse = client.searchTemplate(request, RequestOptions.DEFAULT);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    SearchResponse searchResponse = searchTemplateResponse.getResponse();

    // 添加到list中
    List<String> list = new LinkedList<String>();
    SearchHits hits = searchResponse.getHits();
    SearchHit[] searchHits = hits.getHits();
    for (SearchHit hit : searchHits) {
        list.add(hit.getSourceAsString());
    }
    return list;
}

/**
 * getRestHighLevelClient
 * 其中 ES_URL指的是ES服务器的地址,ES_PORT即端口号,
 * @return
 */
public static RestHighLevelClient getRestHighLevelClient() {
    RestHighLevelClient client = new RestHighLevelClient(
            RestClient.builder(new HttpHost(ES_URL, ES_PORT, "http")));
    return client;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62

任意位置?

这个例子是以"abcd*"为例,但是怎么做到任意位置模糊呢?只需要更改 " * " 的位置就可以了,当然,如果通配符在中间,那么这个方法需要传入两个参数。

总结

使用query很简单,但是一定要查询官网找到相应的文档,然后进行操作。

有什么问题欢迎留言!

Smileyan
2019年8月20日

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号