Sitemap
Eta

Eta

Mm

7 min readMay 13, 2026
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
import co.elastic.clients.elasticsearch._types.mapping.Property;
import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkResponseItem;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.ExistsRequest;
import co.elastic.clients.json.JsonData;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
* Elasticsearch 8.13.0 Kapsamli Ornek
* --------------------------------------------
* Bu ornekte e-ticaret urun katalogu uzerinden:
* 1. Baglanti kurma
* 2. Index olusturma (custom mapping ile)
* 3. Tekli ve toplu (bulk) dokuman ekleme
* 4. CRUD (get, update, delete)
* 5. Cesitli sorgular (match, term, range, bool, wildcard, fuzzy, multi_match)
* 6. Sayfalama ve siralama
* 7. Aggregation (gruplama, ortalama, min/max)
* 8. Index silme (cleanup)
*
* Calistirma:
* - Elasticsearch 8.13.x sunucusu calisiyor olmali
* - Asagidaki HOST, PORT, USER, PASS degerlerini kendi ortamina gore guncelle
*/
public class ElasticsearchDemo {

// ---- Baglanti ayarlari -------------------------------------------------
private static final String HOST = "localhost";
private static final int PORT = 9200;
private static final String SCHEME = "http"; // HTTPS ise "https"
private static final String INDEX = "products";

public static void main(String[] args) throws Exception {

// 1) CLIENT OLUSTURMA -----------------------------------------------
RestClient restClient = RestClient
.builder(new HttpHost(HOST, PORT, SCHEME))
.build();

ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());

ElasticsearchClient client = new ElasticsearchClient(transport);

System.out.println("=> Baglanti kuruldu: " + client.info().version().number());

try {
// 2) INDEX OLUSTURMA (mapping ile) -------------------------------
createIndexWithMapping(client);

// 3) TEKLI DOKUMAN EKLEME ----------------------------------------
indexSingleProduct(client);

// 4) BULK INSERT (toplu ekleme) ----------------------------------
bulkInsertProducts(client);

// ES'in yeni dokumanlari aranabilir yapmasi icin kisa bekleme
client.indices().refresh(r -> r.index(INDEX));

// 5) GET (id ile okuma) ------------------------------------------
getProductById(client, "1");

// 6) UPDATE ------------------------------------------------------
updateProductPrice(client, "1", 27500.0);

// 7) SORGULAR ----------------------------------------------------
matchQuery(client); // full-text arama
termQuery(client); // exact match (keyword)
rangeQuery(client); // fiyat araligi
boolQuery(client); // birden fazla kriteri birlestir
wildcardQuery(client); // joker karakter
fuzzyQuery(client); // yazim hatasina tolerans
multiMatchQuery(client); // birden fazla alanda arama
paginatedSortedSearch(client); // sayfalama + siralama

// 8) AGGREGATION -------------------------------------------------
categoryAggregation(client);
priceStatsAggregation(client);

// 9) DELETE ------------------------------------------------------
deleteProduct(client, "5");

// 10) CLEANUP (istege bagli) -------------------------------------
// deleteIndex(client);

} finally {
transport.close();
restClient.close();
System.out.println("\n=> Baglanti kapatildi.");
}
}

// =======================================================================
// 2) INDEX OLUSTURMA
// =======================================================================
private static void createIndexWithMapping(ElasticsearchClient client) throws Exception {
boolean exists = client.indices()
.exists(ExistsRequest.of(e -> e.index(INDEX)))
.value();

if (exists) {
System.out.println("=> '" + INDEX + "' index'i zaten var, yeniden olusturuluyor...");
client.indices().delete(d -> d.index(INDEX));
}

// Mapping: hangi alan nasil indekslenecek?
// - name: full-text arama (text) + sort/agg icin keyword
// - category: tam eslesme icin keyword
// - price: sayisal araliklar icin double
// - stock: integer
// - tags: keyword (etiket listesi)
// - createdAt: tarih
// - description: full-text
TypeMapping mapping = TypeMapping.of(m -> m
.properties("name", Property.of(p -> p
.text(t -> t.fields("keyword",
Property.of(k -> k.keyword(kw -> kw.ignoreAbove(256)))))))
.properties("category", Property.of(p -> p.keyword(k -> k)))
.properties("price", Property.of(p -> p.double_(d -> d)))
.properties("stock", Property.of(p -> p.integer(i -> i)))
.properties("tags", Property.of(p -> p.keyword(k -> k)))
.properties("createdAt", Property.of(p -> p.date(d -> d)))
.properties("description", Property.of(p -> p.text(t -> t)))
);

CreateIndexResponse resp = client.indices().create(c -> c
.index(INDEX)
.mappings(mapping)
.settings(s -> s
.numberOfShards("1")
.numberOfReplicas("0"))
);

System.out.println("=> Index olusturuldu: " + resp.index() + " (acknowledged=" + resp.acknowledged() + ")");
}

// =======================================================================
// 3) TEKLI EKLEME
// =======================================================================
private static void indexSingleProduct(ElasticsearchClient client) throws Exception {
Product p = new Product(
"1",
"MacBook Pro 14",
"laptop",
64999.0,
15,
Arrays.asList("apple", "m3", "pro"),
LocalDate.now().toString(),
"Apple M3 Pro cipli, 14 inc Liquid Retina XDR ekranli profesyonel laptop."
);

IndexResponse resp = client.index(i -> i
.index(INDEX)
.id(p.getId())
.document(p));

System.out.println("=> Tekli ekleme: id=" + resp.id() + " result=" + resp.result());
}

// =======================================================================
// 4) BULK INSERT
// =======================================================================
private static void bulkInsertProducts(ElasticsearchClient client) throws Exception {
List<Product> products = Arrays.asList(
new Product("2", "Dell XPS 15", "laptop", 45999.0, 8,
Arrays.asList("dell", "intel", "oled"), "2025-11-10",
"Intel Core Ultra 9 islemcili, OLED ekranli ust segment laptop."),
new Product("3", "Logitech MX Master 3S", "aksesuar", 2899.0, 50,
Arrays.asList("mouse", "wireless", "ergonomic"), "2024-05-20",
"Sessiz tiklamali, ileri seviye ergonomik kablosuz mouse."),
new Product("4", "iPhone 15 Pro", "telefon", 64999.0, 25,
Arrays.asList("apple", "5g", "titanium"), "2024-09-15",
"Titanyum kasali, A17 Pro cipli amiral gemisi akilli telefon."),
new Product("5", "Samsung Galaxy S24", "telefon", 49999.0, 30,
Arrays.asList("samsung", "android", "5g"), "2024-01-25",
"Yapay zeka ozellikleriyle gelen yeni nesil Android telefon."),
new Product("6", "Sony WH-1000XM5", "aksesuar", 12499.0, 18,
Arrays.asList("headphone", "noise-cancelling", "bluetooth"), "2023-06-01",
"Sektor lideri aktif gurultu engelleme ozelliklh kulaklik."),
new Product("7", "Lenovo ThinkPad X1", "laptop", 52000.0, 5,
Arrays.asList("lenovo", "business", "intel"), "2025-03-15",
"Is dunyasi icin tasarlanmis dayanikli ve hafif laptop."),
new Product("8", "Apple Watch Series 9", "aksesuar", 16999.0, 40,
Arrays.asList("apple", "wearable", "health"), "2024-09-22",
"Saglik takibi ve fitness ozellikleri ile akilli saat.")
);

BulkRequest.Builder br = new BulkRequest.Builder();
for (Product p : products) {
br.operations(op -> op
.index(idx -> idx
.index(INDEX)
.id(p.getId())
.document(p)));
}

BulkResponse result = client.bulk(br.build());

if (result.errors()) {
System.out.println("=> Bulk'ta hatalar var:");
for (BulkResponseItem item : result.items()) {
if (item.error() != null) {
System.out.println(" - " + item.error().reason());
}
}
} else {
System.out.println("=> Bulk ekleme basarili: " + result.items().size() + " dokuman, sure=" + result.took() + "ms");
}
}

// =======================================================================
// 5) GET
// =======================================================================
private static void getProductById(ElasticsearchClient client, String id) throws Exception {
GetResponse<Product> resp = client.get(g -> g
.index(INDEX)
.id(id), Product.class);

if (resp.found()) {
System.out.println("=> GET id=" + id + " -> " + resp.source().getName()
+ " | fiyat=" + resp.source().getPrice());
} else {
System.out.println("=> GET id=" + id + " bulunamadi.");
}
}

// =======================================================================
// 6) UPDATE
// =======================================================================
private static void updateProductPrice(ElasticsearchClient client, String id, double newPrice) throws Exception {
UpdateResponse<Product> resp = client.update(u -> u
.index(INDEX)
.id(id)
.doc(Map.of("price", newPrice)),
Product.class);

System.out.println("=> UPDATE id=" + id + " yeni fiyat=" + newPrice + " result=" + resp.result());
}

// =======================================================================
// 7a) MATCH QUERY - full-text arama
// =======================================================================
private static void matchQuery(ElasticsearchClient client) throws Exception {
System.out.println("\n--- MATCH QUERY: aciklamada 'profesyonel' gecenler ---");

SearchResponse<Product> resp = client.search(s -> s
.index(INDEX)
.query(q -> q
.match(m -> m
.field("description")
.query("profesyonel"))), Product.class);

printHits(resp);
}

// =======================================================================
// 7b) TERM QUERY - exact match (keyword)
// =======================================================================
private static void termQuery(ElasticsearchClient client) throws Exception {
System.out.println("\n--- TERM QUERY: category = 'laptop' ---");

SearchResponse<Product> resp = client.search(s -> s
.index(INDEX)
.query(q -> q
.term(t -> t
.field("category")
.value("laptop"))), Product.class);

printHits(resp);
}

// =======================================================================
// 7c) RANGE QUERY - sayisal aralik
// =======================================================================
private static void rangeQuery(ElasticsearchClient client) throws Exception {
System.out.println("\n--- RANGE QUERY: 10.000 - 50.000 TL arasi urunler ---");

SearchResponse<Product> resp = client.search(s -> s
.index(INDEX)
.query(q -> q
.range(r -> r
.field("price")
.gte(JsonData.of(10000))
.lte(JsonData.of(50000)))), Product.class);

printHits(resp);
}

// =======================================================================
// 7d) BOOL QUERY - birden fazla kriteri birlestir
// =======================================================================
private static void boolQuery(ElasticsearchClient client) throws Exception {
System.out.println("\n--- BOOL QUERY: kategori=laptop VE fiyat<60000 VE stok>0 ---");

Query categoryQuery = Query.of(q -> q
.term(t -> t.field("category").value("laptop")));

Query priceQuery = Query.of(q -> q
.range(r -> r.field("price").lt(JsonData.of(60000))));

Query stockQuery = Query.of(q -> q
.range(r -> r.field("stock").gt(JsonData.of(0))));

SearchResponse<Product> resp = client.search(s -> s
.index(INDEX)
.query(q -> q
.bool(b -> b
.must(categoryQuery)
.filter(priceQuery)
.filter(stockQuery))), Product.class);

printHits(resp);
}

// =======================================================================
// 7e) WILDCARD - joker karakter
// =======================================================================
private static void wildcardQuery(ElasticsearchClient client) throws Exception {
System.out.println("\n--- WILDCARD QUERY: name.keyword ile 'Apple*' ---");

SearchResponse<Product> resp = client.search(s -> s
.index(INDEX)
.query(q -> q
.wildcard(w -> w
.field("name.keyword")
.value("Apple*"))), Product.class);

printHits(resp);
}

// =======================================================================
// 7f) FUZZY - yazim hatasina tolerans
// =======================================================================
private static void fuzzyQuery(ElasticsearchClient client) throws Exception {
System.out.println("\n--- FUZZY QUERY: 'lapton' (laptop yerine) ---");

SearchResponse<Product> resp = client.search(s -> s
.index(INDEX)
.query(q -> q
.fuzzy(f -> f
.field("category")
.value("lapton")
.fuzziness("AUTO"))), Product.class);

printHits(resp);
}

// =======================================================================
// 7g) MULTI MATCH - birden fazla alanda ara
// =======================================================================
private static void multiMatchQuery(ElasticsearchClient client) throws Exception {
System.out.println("\n--- MULTI MATCH: 'apple' kelimesi name + description + tags ---");

SearchResponse<Product> resp = client.search(s -> s
.index(INDEX)
.query(q -> q
.multiMatch(mm -> mm
.query("apple")
.fields("name^3", "description", "tags"))), Product.class);
// ^3 -> name alani 3 kat agirlikli

printHits(resp);
}

// =======================================================================
// 7h) PAGINATION + SORT
// =======================================================================
private static void paginatedSortedSearch(ElasticsearchClient client) throws Exception {
System.out.println("\n--- PAGINATION: sayfa 1, boyut 3, fiyata gore azalan ---");

SearchResponse<Product> resp = client.search(s -> s
.index(INDEX)
.from(0)
.size(3)
.sort(so -> so
.field(f -> f.field("price").order(SortOrder.Desc)))
.query(q -> q.matchAll(m -> m)), Product.class);

printHits(resp);
System.out.println(" (Toplam eslesen: " + resp.hits().total().value() + ")");
}

// =======================================================================
// 8a) AGGREGATION - kategoriye gore grupla (terms)
// =======================================================================
private static void categoryAggregation(ElasticsearchClient client) throws Exception {
System.out.println("\n--- AGGREGATION: kategoriye gore urun sayisi ---");

SearchResponse<Void> resp = client.search(s -> s
.index(INDEX)
.size(0) // doc istemiyoruz, sadece aggregation
.aggregations("by_category", a -> a
.terms(t -> t.field("category"))), Void.class);

Aggregate agg = resp.aggregations().get("by_category");
agg.sterms().buckets().array().forEach(b ->
System.out.println(" " + b.key().stringValue() + " -> " + b.docCount() + " urun"));
}

// =======================================================================
// 8b) AGGREGATION - fiyat istatistikleri
// =======================================================================
private static void priceStatsAggregation(ElasticsearchClient client) throws Exception {
System.out.println("\n--- AGGREGATION: fiyat istatistikleri ---");

SearchResponse<Void> resp = client.search(s -> s
.index(INDEX)
.size(0)
.aggregations("price_stats", a -> a
.stats(st -> st.field("price"))), Void.class);

var stats = resp.aggregations().get("price_stats").stats();
System.out.println(" Adet : " + stats.count());
System.out.println(" Min : " + stats.min());
System.out.println(" Max : " + stats.max());
System.out.println(" Ort. : " + String.format("%.2f", stats.avg()));
System.out.println(" Top. : " + stats.sum());
}

// =======================================================================
// 9) DELETE
// =======================================================================
private static void deleteProduct(ElasticsearchClient client, String id) throws Exception {
DeleteResponse resp = client.delete(d -> d.index(INDEX).id(id));
System.out.println("\n=> DELETE id=" + id + " result=" + resp.result());
}

// =======================================================================
// 10) CLEANUP
// =======================================================================
@SuppressWarnings("unused")
private static void deleteIndex(ElasticsearchClient client) throws Exception {
client.indices().delete(d -> d.index(INDEX));
System.out.println("=> Index silindi: " + INDEX);
}

// =======================================================================
// YARDIMCI
// =======================================================================
private static void printHits(SearchResponse<Product> resp) {
List<Hit<Product>> hits = resp.hits().hits();
if (hits.isEmpty()) {
System.out.println(" (sonuc yok)");
return;
}
for (Hit<Product> h : hits) {
Product p = h.source();
System.out.printf(" [%s] %-22s | %-9s | %8.2f TL | stok=%d%n",
h.id(), p.getName(), p.getCategory(), p.getPrice(), p.getStock());
}
}

// =======================================================================
// MODEL
// =======================================================================
public static class Product {
@JsonProperty("id") private String id;
@JsonProperty("name") private String name;
@JsonProperty("category") private String category;
@JsonProperty("price") private double price;
@JsonProperty("stock") private int stock;
@JsonProperty("tags") private List<String> tags;
@JsonProperty("createdAt") private String createdAt;
@JsonProperty("description") private String description;

public Product() {}

public Product(String id, String name, String category, double price, int stock,
List<String> tags, String createdAt, String description) {
this.id = id;
this.name = name;
this.category = category;
this.price = price;
this.stock = stock;
this.tags = tags;
this.createdAt = createdAt;
this.description = description;
}

public String getId() { return id; }
public String getName() { return name; }
public String getCategory() { return category; }
public double getPrice() { return price; }
public int getStock() { return stock; }
public List<String> getTags() { return tags; }
public String getCreatedAt() { return createdAt; }
public String getDescription() { return description; }

public void setId(String id) { this.id = id; }
public void setName(String name) { this.name = name; }
public void setCategory(String category) { this.category = category; }
public void setPrice(double price) { this.price = price; }
public void setStock(int stock) { this.stock = stock; }
public void setTags(List<String> tags) { this.tags = tags; }
public void setCreatedAt(String createdAt) { this.createdAt = createdAt; }
public void setDescription(String description) { this.description = description; }
}
}

--

--