DeleteRequest example with elastic java api client 8.2.0 - elasticsearch

I need example for DeleteRequest with respect to ES 8.2.0 Java Api client where we don't have type. we have only index and documents. I am looking for code reference where I want to delete one particular document by passing index name and doc id.

You can use below code for deleting document from index. You need to provide index_name and doc_id to delete document.
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient esClient = new ElasticsearchClient(transport);
DeleteRequest request = DeleteRequest.of(d -> d.index("index_name").id("doc_id"));
DeleteResponse response = esClient.delete(request);

you can try this out
Syntax:
DeleteRequest request = new DeleteRequest("your-index-name","doc-id");
Example:
DeleteRequest deleteRequest = new DeleteRequest("employeeindex","002");
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println("response id: "+deleteResponse.getId());
for more information
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-document-delete.html

Related

ElasticSearch new Java API print created quesy

I trying out the new Java Client for Elastic 8.1.1.
In older versions i was able to print out the generated json query by using searchRequest.source().
I cannot find out actuallay what methode/service i can use do to so with the new client.
My code looks:
final Query range_query = new Query.Builder().range(r -> r.field("pixel_x")
.from(String.valueOf(lookupDto.getPixel_x_min())).to(String.valueOf(lookupDto.getPixel_x_max())))
.build();
final Query bool_query = new Query.Builder().bool(t -> t.must(range_query)).build();
SearchRequest sc = SearchRequest.of(s -> s.query(bool_query).index(INDEX).size(100));
The SearchRequest object offers a source() method but ist value is null.
You can use below code for printing query with new Elastic Java Client:
Query termQuery = TermQuery.of(t -> t.field("field_name").value("search_value"))._toQuery();
StringWriter writer = new StringWriter();
JsonGenerator generator = JacksonJsonProvider.provider().createGenerator(writer);
termQuery.serialize(generator, new JacksonJsonpMapper());
generator.flush();
System.out.println(writer.toString());

Elasticsearch Nest 6 - Get index metadata

Currently, I can retrieve the index mapping metadata from the following command on Kibana
GET /[indexName]/_mapping/[documentType]
Is there a way to do that on Elasticsearch Nest Client? If not, what other options would I have?
You can retrieve it with
var defaultIndex = "default-index";
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var settings = new ConnectionSettings(pool)
.DefaultIndex(defaultIndex);
var client = new ElasticClient(settings);
var mappingResponse = client.GetMapping<MyDocument>();
which will send a request to
GET http://localhost:9200/default-index/_mapping/mydocument
In this case
index will be "default-index", the default index configured on Connection Settings
type will be "mydocument", inferred from the POCO type MyDocument
You can specify index and/or type explicitly if you want to
var mappingResponse = client.GetMapping<MyDocument>(m => m
.Index("foo")
.Type("bar")
);
which sends the following request
GET http://localhost:9200/foo/_mapping/bar
As well as target all indices and/or all types
var mappingResponse = client.GetMapping<MyDocument>(m => m
.AllIndices()
.AllTypes()
);
which sends the following request
GET http://localhost:9200/_mapping

Serialize query from Nest client ElasticSearch 6.4

Till ElasticSearch 6.0 we were able to serialize the search request (object of SearchRequest) to a string
using (System.IO.MemoryStream mStream = new System.IO.MemoryStream())
{
ElasticClient.Serializer.Serialize(searchRequest, mStream);
string rawQueryText = Encoding.ASCII.GetString(mStream.ToArray());
}
Example is here too serialize query from Nest client elastic search 2.3
But in 6.4 version that has been removed and I am not able to locate exactly where is the documentation to serialize the query with 6.4 version
https://github.com/elastic/elasticsearch-net
Can some one help me here?
You can use the extension method in ElasticsearchSerializerExtensions in Elasticsearch.Net
using Elasticsearch.Net;
using Nest;
var client = new ElasticClient();
var searchRequest = new SearchRequest
{
Query = new MatchAllQuery()
};
var json = client.RequestResponseSerializer.SerializeToString(searchRequest);

Elastic search update fails after including null values

We recently upgraded to elastic search v5 and nest v5.6
We are trying to set a field to null, however, the default serialization settings are ignoring null values.
var pool = new SingleNodeConnectionPool(new Uri("http://local:9200"));
var connectionSettings =
new ConnectionSettings(pool)
.DisableDirectStreaming();
var elasticClient = new ElasticClient(connectionSettings);
var indexName = "myIndexName";
var typeName = "myTypeName";
var documentId = 2;
var pendingDescriptor = new BulkDescriptor();
pendingDescriptor.Index(indexName).Type(typeName);
var pendingUpdate = new Dictionary<string, object>
{
{ $"DocumentType_TAG_PENDING_Id", null }
};
var updateRequest = new UpdateRequest<dynamic, dynamic>(indexName, typeName, new Id(documentId));
updateRequest.Doc = pendingUpdate;
elasticClient.Update<dynamic>(updateRequest);
This results in the request:
{"update":{"_id":2,"_retry_on_conflict":3}}
{"doc":{}}
The field value isn't set to null
I tried to modify the serializer to include null values after reading here https://www.elastic.co/guide/en/elasticsearch/client/net-api/5.x/modifying-default-serializer.html
var connectionSettings =
new ConnectionSettings(pool, connection, new SerializerFactory((settings, values) =>
{
settings.NullValueHandling = NullValueHandling.Include;
}));
Now my request becomes:
{"update":{"_index":null,"_type":null,"_id":2,"_version":null,"_version_type":null,"_routing":null,"_parent":null,"_timestamp":null,"_ttl":null,"_retry_on_conflict":3}}
{"doc":{"DocumentType_TAG_PENDING_Id":null},"upsert":null,"doc_as_upsert":null,"script":null,"scripted_upsert":null}
And I get the following error:
{"error":{"root_cause":[{"type":"json_parse_exception","reason":"Current token (VALUE_NULL) not of boolean type\n at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput#181f5854; line: 1, column: 82]"}],"type":"json_parse_exception","reason":"Current token (VALUE_NULL) not of boolean type\n at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput#181f5854; line: 1, column: 82]"},"status":500}
Please help
So far, we have two options:
Upgrade to v6, where they have separated document and request serializers.
So we can customize the way our documents are serialized without affecting the request/response headers. For more info see https://www.elastic.co/guide/en/elasticsearch/client/net-api/master/custom-serialization.html
Use the elastic search low-level client with post request avoid the nest serializer.
https://www.elastic.co/guide/en/elasticsearch/client/net-api/5.x/elasticsearch-net.html
Our preferred way will be to go with the upgrade if everything works and revert to low-level client if any issues

Convert Elastic Search Results to POJO

I have a project using the spring-data-elasticsearch library. I've got my system returning results, but I was wondering how to get my results in the form of my domain POJO class.
I'm not seeing too much documentation on how to accomplish this, but I don't know what the right question I should be Googling for.
Currently, my code looks like this, and in my tests, it retrieves the right results, but not as a POJO.
QueryBuilder matchQuery = QueryBuilders.queryStringQuery(searchTerm).defaultOperator(QueryStringQueryBuilder.Operator.AND);
Client client = elasticsearchTemplate.getClient();
SearchRequestBuilder request = client
.prepareSearch("mediaitem")
.setSearchType(SearchType.QUERY_THEN_FETCH)
.setQuery(matchQuery)
.setFrom(0)
.setSize(100)
.addFields("title", "description", "department");
System.out.println("SEARCH QUERY: " + request.toString());
SearchResponse response = request.execute().actionGet();
SearchHits searchHits = response.getHits();
SearchHit[] hits = searchHits.getHits();
Any help is greatly appreciated.
One option is to use jackson-databind to map JSON from the search hits to POJOs.
For example:
ObjectMapper objectMapper = new ObjectMapper();
SearchHit[] hits = searchHits.getHits();
Arrays.stream(hits).forEach(hit -> {
String source = hit.getSourceAsString();
MediaItem mediaItem = objectMapper.readValue(source, MediaItem.class);
// Use media item...
});

Resources