SpringBoot下使用ElasticSaerch教程(二)
阿新 • • 發佈:2018-11-09
完成的是針對索引Index的增刪改查.環境和前文是一樣的.這裡直接就開始了,前文教程SpringBoot下使用ElasticSearch教程(一).
一:SpringBoot對索引使用有三種方式,json格式(推薦),Map,內建工具(測試使用)的方式.這裡使用內建工具吧.
1. 查詢索引資料.
使用GetResponse來實現.(需求是查詢id=3的資料.)
import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.xcontent.XContentFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; @RequestMapping("/index") @RestController public class IndexController { @Autowired private TransportClient client; @RequestMapping("/get") public String get(){ GetResponse response=client.prepareGet("book","novel","3").get(); System.out.println(response.getSourceAsString()); System.out.println("索引名稱:"+response.getIndex()); System.out.println("型別:"+response.getType()); System.out.println("文件ID:"+response.getId()); return "Get Index Success"; }
測試結果:
2. 建立索引資料.(新增id=14的資料)
@RequestMapping("/create") public String create() throws IOException { IndexResponse response=client.prepareIndex("book","novel","14").setSource(XContentFactory.jsonBuilder().startObject().field("title","Java面向物件程式設計").field("author","Jack").field("word_count",700).field("publish_data","2012-10-15").endObject()).get(); System.out.println("索引名稱:"+response.getIndex()); System.out.println("型別:"+response.getType()); System.out.println("文件ID:"+response.getId()); System.out.println("當前例項狀態:"+response.status()); return "Create Index Success"; }
測試結果:
3. 更新索引資料.(更新id為1的書籍的title)
@RequestMapping("/update") public String update() throws IOException { UpdateResponse response=client.prepareUpdate("book","novel","1").setDoc(XContentFactory.jsonBuilder().startObject().field("title","JavaWeb從入門到精通").endObject()).get(); System.out.println("索引名稱:"+response.getIndex()); System.out.println("型別:"+response.getType()); System.out.println("文件ID:"+response.getId()); System.out.println("當前例項狀態:"+response.status()); return "Update Index Success"; }
測試結果:
4. 刪除索引資料.(刪除索引為14的資料).
@RequestMapping("/delete")
public String delete(){
DeleteResponse response=client.prepareDelete("book", "novel", "14").get();
System.out.println("索引名稱:"+response.getIndex());
System.out.println("型別:"+response.getType());
System.out.println("文件ID:"+response.getId());
System.out.println("當前例項狀態:"+response.status());
return "Delete Index Success";
}
測試結果:
5. 注意事項.
注意修改資料的時候的那個jsonBuilder().
導包: import org.elasticsearch.common.xcontent.XContentFactory;
XContentFactory.jsonBuilder().startObject().field("title","JavaWeb從入門到精通").endObject()).get()
至此完成了基於SpringBoot的簡單的增刪改查.