Я пытаюсь подключить свое Java-приложение к экземпляру Amazon Elastic Search и работать над поиском продуктов, но уже несколько дней у меня ничего не получается, и наконец я прошу вас, ребята, можете ли вы помочь.
Мой экземпляр Elastic Search
{
"name" : "85f0ea170418836832b23ba9381b02e1",
"cluster_name" : "034362065489:atosell",
"cluster_uuid" : "QvnKushRQxKnOqqXwzqq3Q",
"version" : {
"distribution" : "opensearch",
"number" : "2.15.0",
"build_type" : "tar",
"build_hash" : "unknown",
"build_date" : "2024-09-13T11:21:22.242025742Z",
"build_snapshot" : false,
"lucene_version" : "9.10.0",
"minimum_wire_compatibility_version" : "7.10.0",
"minimum_index_compatibility_version" : "7.0.0"
},
"tagline" : "The OpenSearch Project: https://opensearch.org/"
}
Конфигурация эластичного поиска
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchConfiguration;
@Configuration
public class ElasticSearchConfig extends ElasticsearchConfiguration {
@Override
public ClientConfiguration clientConfiguration() {
return ClientConfiguration.builder()
.connectedTo("search-atosell-ezrvtmvhttw6fjztfsgkbndgbu.eu-central-1.es.amazonaws.com:443")
.usingSsl()
.withBasicAuth("username", "password")
.build();
}
}
Мой файл POM:
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
org.springframework.boot
spring-boot-starter-parent
3.3.2
com.app
fluxix
0.0.1-SNAPSHOT
jar
fluxix
Demo project for Spring Boot
21
org.springframework.boot
spring-boot-starter-mail
org.springframework.boot
spring-boot-starter-security
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-validation
org.springdoc
springdoc-openapi-starter-webmvc-ui
2.6.0
org.springframework.data
spring-data-commons
3.3.2
software.amazon.awssdk
dynamodb
2.27.2
software.amazon.awssdk
dynamodb-enhanced
2.27.2
io.jsonwebtoken
jjwt-api
0.12.6
io.jsonwebtoken
jjwt-impl
0.12.6
runtime
io.jsonwebtoken
jjwt-jackson
0.12.6
runtime
com.stripe
stripe-java
26.10.0
org.springframework.boot
spring-boot-starter-data-elasticsearch
org.elasticsearch
elasticsearch
8.15.2
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.springframework.security
spring-security-test
test
org.springframework.boot
spring-boot-maven-plugin
org.projectlombok
lombok
Контроллер продуктов Elastic Search
package com.app.fluxix.elasticsearch.controller;
import com.app.fluxix.elasticsearch.entity.ElasticSearchProduct;
import com.app.fluxix.elasticsearch.service.ElasticSearchProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/elasticsearch/product")
public class ElasticSearchProductController {
@Autowired
private ElasticSearchProductService elasticSearchProductService;
@PostMapping("/add")
public ResponseEntity addProduct(@RequestBody ElasticSearchProduct elasticSearchProduct) {
return ResponseEntity.ok(elasticSearchProductService.addProduct(elasticSearchProduct));
}
@PostMapping("/addMultiple")
public ResponseEntity addProducts(@RequestBody List elasticSearchProducts) {
return ResponseEntity.ok(elasticSearchProductService.addProducts(elasticSearchProducts));
}
@GetMapping("/get/{id}")
public ResponseEntity getProduct(@PathVariable String id) {
ElasticSearchProduct elasticSearchProduct = elasticSearchProductService.getProduct(id);
if (elasticSearchProduct != null) {
return ResponseEntity.ok(elasticSearchProduct);
}
return ResponseEntity.notFound().build();
}
@GetMapping("/getAll")
public ResponseEntity getAllProducts() {
return ResponseEntity.ok(elasticSearchProductService.getAllProducts());
}
@PostMapping("/update/{id}")
public ResponseEntity updateProduct(
@RequestBody ElasticSearchProduct elasticSearchProduct,
@PathVariable String id
) {
ElasticSearchProduct updatedElasticSearchProduct =
elasticSearchProductService.updateProduct(elasticSearchProduct, id);
if (updatedElasticSearchProduct != null) {
return ResponseEntity.ok(updatedElasticSearchProduct);
}
return ResponseEntity.notFound().build();
}
@DeleteMapping("/delete/{id}")
public ResponseEntity deleteProduct(@PathVariable String id) {
elasticSearchProductService.deleteProduct(id);
return ResponseEntity.noContent().build();
}
@DeleteMapping("/deleteMultiple")
public ResponseEntity deleteProducts(@RequestBody List ids) {
elasticSearchProductService.deleteProducts(ids);
return ResponseEntity.noContent().build();
}
@DeleteMapping("/deleteAll")
public ResponseEntity deleteAllProducts() {
elasticSearchProductService.deleteAllProducts();
return ResponseEntity.noContent().build(); // Respond with HTTP 204 No Content
}
@GetMapping("/search/byName")
public ResponseEntity searchByName(@RequestParam String name) {
List elasticSearchProducts = elasticSearchProductService.searchByName(name);
return ResponseEntity.ok(elasticSearchProducts);
}
@GetMapping("/search/byPrice")
public ResponseEntity searchByPrice(@RequestParam Double price) {
List elasticSearchProducts = elasticSearchProductService.searchByPrice(price);
return ResponseEntity.ok(elasticSearchProducts);
}
@GetMapping("/search/byField")
public ResponseEntity searchByField(
@RequestParam String fieldName,
@RequestParam String fieldValue) {
List elasticSearchProducts = elasticSearchProductService.searchByField(fieldName, fieldValue);
return ResponseEntity.ok(elasticSearchProducts);
}
@GetMapping("/search")
public ResponseEntity search(@RequestParam String text) {
List elasticSearchProducts = elasticSearchProductService.searchByText(text);
return ResponseEntity.ok(elasticSearchProducts);
}
}
Служба продукта Elastic Search
package com.app.fluxix.elasticsearch.service;
import com.app.fluxix.elasticsearch.entity.ElasticSearchProduct;
import com.app.fluxix.elasticsearch.repo.ElasticSearchProductRepo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class ElasticSearchProductService {
private static final Logger logger = LoggerFactory.getLogger(ElasticSearchProductService.class);
@Autowired
private ElasticSearchProductRepo elasticSearchProductRepo;
@Autowired
private ElasticsearchOperations elasticsearchOperations;
public ElasticSearchProduct addProduct(ElasticSearchProduct elasticSearchProduct) {
logger.info("Inserting new elasticSearchProduct: {}", elasticSearchProduct.getTitle());
return elasticSearchProductRepo.save(elasticSearchProduct);
}
public List addProducts(List elasticSearchProducts) {
logger.info("Inserting multiple elasticSearchProducts");
return (List) elasticSearchProductRepo.saveAll(elasticSearchProducts);
}
public ElasticSearchProduct getProduct(String id) {
logger.info("Fetching product with ID: {}", id);
Optional productOpt = elasticSearchProductRepo.findById(id);
return productOpt.orElse(null);
}
public Iterable getAllProducts() {
logger.info("Fetching all products");
return elasticSearchProductRepo.findAll();
}
public ElasticSearchProduct updateProduct(ElasticSearchProduct elasticSearchProduct, String id) {
logger.info("Updating elasticSearchProduct with ID: {}", id);
Optional existingProductOpt = elasticSearchProductRepo.findById(id);
if (existingProductOpt.isPresent()) {
ElasticSearchProduct existingElasticSearchProduct = existingProductOpt.get();
existingElasticSearchProduct.setTitle(elasticSearchProduct.getTitle());
existingElasticSearchProduct.setDescription(elasticSearchProduct.getDescription());
return elasticSearchProductRepo.save(existingElasticSearchProduct);
}
logger.error("ElasticSearchProduct with ID: {} not found", id);
return null;
}
public void deleteProduct(String id) {
logger.info("Deleting product with ID: {}", id);
if (elasticSearchProductRepo.existsById(id)) {
elasticSearchProductRepo.deleteById(id);
logger.info("ElasticSearchProduct with ID: {} deleted", id);
} else {
logger.error("ElasticSearchProduct with ID: {} not found", id);
}
}
public void deleteProducts(List ids) {
logger.info("Deleting multiple products with IDs: {}", ids);
Iterable productsToDelete = elasticSearchProductRepo.findAllById(ids);
elasticSearchProductRepo.deleteAll(productsToDelete);
logger.info("Products with IDs: {} deleted", ids);
}
public void deleteAllProducts() {
logger.info("Deleting all products");
elasticSearchProductRepo.deleteAll();
logger.info("All products have been deleted");
}
public List searchByName(String name) {
return elasticSearchProductRepo.findByName(name);
}
public List searchByPrice(Double price) {
return elasticSearchProductRepo.findByPrice(price);
}
public List searchByField(String fieldName, String fieldValue) {
logger.info("Searching products by field: {} with value: {}", fieldName, fieldValue);
Criteria criteria = Criteria.where(fieldName).is(fieldValue);
Query query = new CriteriaQuery(criteria);
return elasticsearchOperations.search(query, ElasticSearchProduct.class).getSearchHits()
.stream()
.map(SearchHit::getContent)
.collect(Collectors.toList());
}
public List searchByText(String text) {
logger.info("Searching products by text: {}", text);
Criteria criteria = new Criteria("name").matches(text)
.or(new Criteria("category").matches(text))
.or(new Criteria("description").matches(text));
Query query = new CriteriaQuery(criteria);
return elasticsearchOperations.search(query, ElasticSearchProduct.class).getSearchHits()
.stream()
.map(SearchHit::getContent)
.collect(Collectors.toList());
}
}
Приведенная ниже ошибка выглядит тревожной, однако ниже также вставлена полная трассировка:
org.elasticsearch.client.ResponseException: method [PUT], host [https://search-atosell-ezrvtmvhttw6fjzt ... ws.com:443], URI [/products], status line [HTTP/1.1 406 Not Acceptable] {"error":"Content-Type header [application/vnd.elasticsearch+json; compatible-with=8] is not supported","status":406}
Трассировка стека ошибок:
"
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.3.2)
org.springframework.data.elasticsearch.repository.support.ElasticsearchRepositoryFactoryBean.afterPropertiesSet(ElasticsearchRepositoryFactoryBean.java:69) ~[spring-data-elasticsearch-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1853) ~[spring-beans-6.1.11.jar:6.1.11]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1802) ~[spring-beans-6.1.11.jar:6.1.11]
... 58 common frames omitted
Caused by: org.springframework.dao.DataAccessResourceFailureException: method [PUT], host [https://search-atosell-ezrvtmvhttw6fjzt ... ws.com:443], URI [/products], status line [HTTP/1.1 406 Not Acceptable]
{"error":"Content-Type header [application/vnd.elasticsearch+json; compatible-with=8] is not supported","status":406}
at org.springframework.data.elasticsearch.client.elc.ElasticsearchExceptionTranslator.translateExceptionIfPossible(ElasticsearchExceptionTranslator.java:111) ~[spring-data-elasticsearch-5.3.2.jar:5.3.2]
at org.springframework.data.elasticsearch.client.elc.ElasticsearchExceptionTranslator.translateException(ElasticsearchExceptionTranslator.java:65) ~[spring-data-elasticsearch-5.3.2.jar:5.3.2]
at org.springframework.data.elasticsearch.client.elc.ChildTemplate.execute(ChildTemplate.java:73) ~[spring-data-elasticsearch-5.3.2.jar:5.3.2]
at org.springframework.data.elasticsearch.client.elc.IndicesTemplate.doCreate(IndicesTemplate.java:145) ~[spring-data-elasticsearch-5.3.2.jar:5.3.2]
at org.springframework.data.elasticsearch.client.elc.IndicesTemplate.createWithMapping(IndicesTemplate.java:135) ~[spring-data-elasticsearch-5.3.2.jar:5.3.2]
at org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository.createIndexAndMappingIfNeeded(SimpleElasticsearchRepository.java:94) ~[spring-data-elasticsearch-5.3.2.jar:5.3.2]
at org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository.(SimpleElasticsearchRepository.java:87) ~[spring-data-elasticsearch-5.3.2.jar:5.3.2]
at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:62) ~[na:na]
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:502) ~[na:na]
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:486) ~[na:na]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:208) ~[spring-beans-6.1.11.jar:6.1.11]
... 71 common frames omitted
Caused by: java.lang.RuntimeException: method [PUT], host [https://search-atosell-ezrvtmvhttw6fjzt ... ws.com:443], URI [/products], status line [HTTP/1.1 406 Not Acceptable]
{"error":"Content-Type header [application/vnd.elasticsearch+json; compatible-with=8] is not supported","status":406}
at
Process finished with exit code 1
Подробнее здесь: https://stackoverflow.com/questions/790 ... using-java
Невозможно использовать эластичный поиск с помощью Java ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Apache Spark установил dataFrame из базы данных Oracle в эластичный поиск
Anonymous » » в форуме Python - 0 Ответы
- 102 Просмотры
-
Последнее сообщение Anonymous
-