首页 > 解决方案 > ElasticSearch 使字段不可从 java 中搜索

问题描述

我目前正在通过我的 java Application 进行弹性搜索。我知道如何使用 RestHighLevelClient 索引 Java pojo。我怎样才能只在新领域而不是完整的pojo上进行搜索。?

    public class Employee{ 
        private long id;
        private String name;
        private String designation;
        private String address;       //want to index but not searchable in elastic search    
     }

我的索引代码如下,运行良好:

 public String saveToEs(Employee employee) throws IOException {
    Map<String, Object> map = objectMapper.convertValue(employee, Map.class);

    IndexRequest indexRequest =
        new IndexRequest(INDEX, TYPE, employee.getId().toString()).source(map, XContentType.JSON);


    IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);

我需要在 java 中执行此操作。请提供帮助或好的链接?

标签: javaelasticsearchresthighlevelclient

解决方案


在地址字段上使用index 选项为 false,默认情况下为 true 以使其不可搜索。正如在同一个官方 ES 链接中提到的:

index 选项控制字段值是否被索引。它接受真或假,默认为真。未编入索引的字段不可查询。

让我向您展示如何使用 REST API 测试它,然后使用 java 代码(使用 REST 高级客户端)来完成它。

映射

{
    "mappings": {
        "properties": {
            "id": {
                "type": "long"
            },
            "name": {
                "type": "text"
            },
            "designation": {
                "type": "text"
            },
            "address": {
                "type": "text",
                "index" : false --> made `index` to false
            }
        }
    }
}

索引几个文档

{
    "address" : "USA",
    "name"  : "Noshaf",
    "id" :  234567892,
    "designation" : "software engineer"
}

{
    "address" : "USA california state",
    "name"  : "opster",
    "id" :  234567890,
    "designation" : "software engineer"
}

address字段上 JSON 格式的简单匹配搜索查询

{
    "query": {
        "match" : {
            "address" : "USA"
        }
    }
}

来自 Elasticsearch 的例外明确提到,它不可搜索

“caused_by”:{“type”:“illegal_argument_exception”,“reason”:“无法搜索字段 [address],因为它没有被索引。” }


推荐阅读