update drug set state where storeId=转为Springboot ES处理
To update the state of a drug in the drug table based on the storeId using Spring Boot and Elasticsearch, follow these steps:
- Create a new class called DrugService to handle the CRUD operations for the Drug entity.
@Service
public class DrugService {
@Autowired
private ElasticsearchOperations elasticsearchOperations;
public void updateDrugState(String storeId, String newState) {
QueryBuilder queryBuilder = QueryBuilders.matchQuery("storeId", storeId);
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(queryBuilder)
.build();
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.doc("state", newState);
elasticsearchOperations.update(searchQuery, updateRequest, IndexCoordinates.of("drug"));
}
}
- Inject the DrugService into your controller class and call the updateDrugState method.
@RestController
@RequestMapping("/drugs")
public class DrugController {
@Autowired
private DrugService drugService;
@PutMapping("/{storeId}")
public ResponseEntity<?> updateDrugState(@PathVariable String storeId, @RequestParam String newState) {
drugService.updateDrugState(storeId, newState);
return ResponseEntity.ok().build();
}
}
- Configure Elasticsearch in your Spring Boot application.properties file.
spring.data.elasticsearch.cluster-name=my-cluster
spring.data.elasticsearch.cluster-nodes=localhost:9300
- Create an Elasticsearch index for the drug entity.
@Configuration
public class ElasticsearchConfig {
@Autowired
private ElasticsearchOperations elasticsearchOperations;
@PostConstruct
public void init() {
elasticsearchOperations.indexOps(Drug.class).create();
}
}
With these changes, you can now update the state of a drug by making a PUT request to "/drugs/{storeId}?newState={newState}". The DrugService will handle the update operation using Elasticsearch.
原文地址: https://www.cveoy.top/t/topic/jfCP 著作权归作者所有。请勿转载和采集!