ElasticSearch Java API-Create an index

Source: Internet
Author: User

ElasticSearch JAVA API Official document: Https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-index.html

First, generate JSON

The first step in creating an index is to convert the object to a JSON string. There are four ways to create JSON documents:

1.1 Handwriting Style generation
String json = "{" +        "\"user\":\"kimchy\"," +        "\"postDate\":\"2013-01-30\"," +        "\"message\":\"trying out Elasticsearch\"" +    "}";

Handwriting is simple, but note the date format: Date formate

1.2 Using Collections

A collection is a Key:value data type that can represent a JSON structure.

Map<StringObjectnew HashMap<StringObject>();json.put("user","kimchy");json.put("postDate",newDate());json.put("message","trying out Elasticsearch");
1.3 Use of Jackson serialization

Elasticsearch has used Jackson and can use it directly to convert JavaBean to JSON.

// instance a json mappernew// create once, reuse// generate jsonbyte[] json = mapper.writeValueAsBytes(yourbeaninstance);
1.4 Using the Elasticsearch Help class
import static Org .common  .xcontent  . * Xcontentbuilder builder = Jsonbuilder () .startobject  () .field  (, " Kimchy ") .field         ( "postdate" , New Date ()) .field  ( "message" ,  "trying out Elasticsearch" ) .endobject  () String json = Builder.string  ( )   
Second, create an index

The following example writes a JSON document so the index library is named Twitter, and the type Tweet,id is 1:

Import static Org. Elasticsearch. Common. Xcontent. Xcontentfactory.*;Indexresponse response = Client. Prepareindex("Twitter","tweet","1"). SetSource(Jsonbuilder (). StartObject(). Field("User","Kimchy"). Field("Postdate", new Date ()). Field("Message","trying out Elasticsearch"). EndObject()                  ). Get();

You can also directly descendant a JSON string:

String"{" +        "\"user\":\"kimchy\"," +        "\"postDate\":\"2013-01-30\"," +        "\"message\":\"trying out Elasticsearch\"" +    "}"response = client.prepareIndex("twitter""tweet")        .setSource(json)        .get();

You can call the methods of the response object to get the return information:

// 索引名称String _index = response.getIndex();// 类型名称String _type = response.getType();// 文档idString _id = response.getId();// 版本(if it‘stime1)long _version = response.getVersion();// 是否被创建isifisnewif it has been updatedboolean created = response.isCreated();

It's easier to System.out.println(response) see the return information directly.

Third, Java implementation

Create a new Java project and import the jar file under the Elasticsearch-2.3.3/lib directory. Create a new blog class:

publicclass Blog {    private Integer id;    private String title;    private String posttime;    private String content;    publicBlog() {    }    publicBlog(Integer id, String title, String posttime, String content) {        this.id = id;        this.title = title;        this.posttime = posttime;        this.content = content;    }  //setter and getter  }

To create a Java entity class to JSON tool class:

Import Java. IO. IOException;import org. Elasticsearch. Common. Xcontent. Xcontentbuilder;import org. Elasticsearch. Common. Xcontent. Xcontentfactory;public class Jsonutil {//Java Entity object to JSON object public static string Model2json (blog blog) {string jsondata = nul L;try {xcontentbuilder Jsonbuild = xcontentfactory. Jsonbuilder();Jsonbuild. StartObject(). Field("id", blog. GetId()). Field("title", blog. GetTitle()). Field("Posttime", blog. Getposttime()). Field("Content", blog. GetContent()). EndObject();Jsondata = Jsonbuild. String();System. out. println(Jsondata);} catch (IOException e) {E. Printstacktrace();} return Jsondata;}}

Add data to return a list:

ImportJava.Util.ArrayList;ImportJava.Util.Date;ImportJava.Util.List; PublicClass DataFactory { PublicStatic DataFactory DataFactory= NewDataFactory ();PrivateDataFactory () {} PublicDataFactory getinstance () {returnDataFactory; } PublicStaticList<String>Getinitjsondata () {List<String> List = NewArrayList<String>();StringData1=Jsonutil.Model2json (NewBlog (1,"Introduction to Git","2016-06-19","The main difference between SVN and git ..."));StringData2=Jsonutil.Model2json (NewBlog (2,"Introduction and simple use of generics in Java","2016-06-19","Learning objectives to master the meaning of generics ..."));StringData3=Jsonutil.Model2json (NewBlog (3,"SQL basic Operations","2016-06-19","Basic operation: CRUD ..."));StringData4=Jsonutil.Model2json (NewBlog (4,"Hibernate Framework Basics","2016-06-19","Hibernate framework Basics ..."));StringData5=Jsonutil.Model2json (NewBlog (5,"Shell Basics","2016-06-19","What the shell is ..."));List.Add (data1);List.Add (DATA2);List.Add (DATA3);List.Add (DATA4);List.Add (DATA5);return List; }}

To create an index, add data:

Import Java. IO. IOException;Import Java. NET. InetAddress;Import Java. NET. Unknownhostexception;Import Java. Util. Date;Import Java. Util. List;import org. Elasticsearch. Action. Index. Indexresponse;import org. Elasticsearch. Client. Client;import org. Elasticsearch. Client. Transport. Transportclient;import org. Elasticsearch. Common. Transport. Inetsockettransportaddress;import org. Elasticsearch. Common. Xcontent. Xcontentbuilder;Import CN. com. Bropen. Entity. DataFactory;Import static Org. Elasticsearch. Common. Xcontent. Xcontentfactory.*;public class Elasticsearchhandler {public static void main (string[] args) {try {/ * Create client * /Client Startup Client client = Transportclient. Builder(). Build(). Addtransportaddress(New Inetsockettransportaddress (inetaddress. Getbyname("127.0.0.1"),9300));Xcontentbuilder builder = Jsonbuilder (). StartObject(). Field("User","Kimchy"). Field("Postdate", new Date ()). Field("Message","trying out Elasticsearch"). EndObject();list<string> Jsondata = DataFactory. Getinitjsondata();for (int i =0; i < jsondata.size (); i++) {Indexresponse response = Client. Prepareindex("Blog","article"). SetSource(Jsondata. Get(i)). Get();if (response. iscreated()) {System. out. println("created successfully!");}} Client. Close();} catch (Unknownhostexception e) {E. Printstacktrace();} catch (IOException e) {E. Printstacktrace();}    }}

To view the inserted data:

ElasticSearch Java API-Create an index

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.