我目前正在通过java应用程序进行弹性搜索。我知道如何使用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中执行此操作。请提供任何帮助或良好链接?
答案 0 :(得分:1)
在地址字段上将index option设置为false,默认情况下为true,以使其不可搜索。如同一官方ES链接中所述:
索引选项控制是否对字段值建立索引。它接受 true或false,默认为true。未索引的字段是 不可查询。
让我向您展示如何使用REST API进行测试,然后再使用Java代码(使用Rest-High-Level Client)进行测试。
{
"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"
}
}
}
“ caused_by”:{ “ type”:“ illegal_argument_exception”, “原因”:“ 由于未编入字段[地址] ,因此无法搜索。” }
答案 1 :(得分:1)
为RestHighLevelClient
写另一个答案,因为另一个答案对于不使用Rest客户端的人很有用,并且在第一个答案中添加该答案会太长。
注意:您传递的是type
,它在ES 7.X中已弃用,并且我使用的是ES 7.X版本,因此我的代码符合7.X。
CreateIndexRequest request = new CreateIndexRequest("employee");
Map<String, Object> name = new HashMap<>();
name.put("type", "text");
Map<String, Object> address = new HashMap<>();
address.put("type", "text");
address.put("index", false);
Map<String, Object> properties = new HashMap<>();
properties.put("name", name);
properties.put("address", address);
Map<String, Object> mapping = new HashMap<>();
mapping.put("properties", properties);
request.mapping(mapping);
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
address
字段,该字段不可搜索,而我使用的address.put("index", false);
字段则可搜索name
字段,并且此选项不存在。index mapping
。index: false
。{ "employee": { "mappings": { "properties": { "address": { "type": "text", "index": false }, "name": { "type": "text" } } } } }