当前内容用于本人学习和巩固Elasticsearch,当前的内容基于前面的安装和使用Elasticsearch操作,这里的内容为简单的使用java方式操作当前的Elasticsearch
由于返回的响应为InputStream,所以需要解析流为String来进行输出
这里有一个小工具IOUtls
package com.hy.elasticsearch.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import org.apache.commons.codec.Charsets;
/**
* @author hy
* @description 通用的流工具
*/
public abstract class IOUtils {
private static final int EOF = -1;
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
public static void writeFile(final InputStream in, final OutputStream os) throws IOException {
byte[] buffer = new byte[1024];
int start = 0;
try {
while ((start = in.read(buffer)) != -1) {
os.write(buffer, 0, start);
}
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
closeStream(in);
closeStream(os);
}
}
public static void closeStream(final InputStream in) {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void closeStream(final OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static InputStream getInputStreamByFile(final File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (file.canRead() == false) {
throw new IOException("File '" + file + "' cannot be read");
}
} else {
throw new FileNotFoundException("File '" + file + "' does not exist");
}
return new FileInputStream(file);
}
public static String toString(InputStream input) throws IOException {
try {
return toString(input, Charset.defaultCharset());
} finally {
closeStream(input);
}
}
public static String toString(InputStream input, Charset encoding) throws IOException {
StringBuilderWriter sw = new StringBuilderWriter();
copy(input, sw, encoding);
return sw.toString();
}
public static void copy(InputStream input, Writer output, Charset encoding) throws IOException {
InputStreamReader in = new InputStreamReader(input, encoding);
copy(in, output);
}
public static int copy(Reader input, Writer output) throws IOException {
long count = copyLarge(input, output);
if (count > Integer.MAX_VALUE) {
return -1;
}
return (int) count;
}
public static long copyLarge(Reader input, Writer output) throws IOException {
return copyLarge(input, output, new char[DEFAULT_BUFFER_SIZE]);
}
public static long copyLarge(Reader input, Writer output, char[] buffer) throws IOException {
long count = 0;
int n = 0;
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
}
以及一个StringBuilderWriter
package com.hy.elasticsearch.util;
import java.io.Serializable;
import java.io.Writer;
public class StringBuilderWriter extends Writer implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private final StringBuilder builder;
/**
* Construct a new {@link StringBuilder} instance with default capacity.
*/
public StringBuilderWriter() {
this.builder = new StringBuilder();
}
/**
* Construct a new {@link StringBuilder} instance with the specified capacity.
*
* @param capacity The initial capacity of the underlying {@link StringBuilder}
*/
public StringBuilderWriter(int capacity) {
this.builder = new StringBuilder(capacity);
}
/**
* Construct a new instance with the specified {@link StringBuilder}.
*
* @param builder The String builder
*/
public StringBuilderWriter(StringBuilder builder) {
this.builder = builder != null ? builder : new StringBuilder();
}
/**
* Append a single character to this Writer.
*
* @param value The character to append
* @return This writer instance
*/
@Override
public Writer append(char value) {
builder.append(value);
return this;
}
/**
* Append a character sequence to this Writer.
*
* @param value The character to append
* @return This writer instance
*/
@Override
public Writer append(CharSequence value) {
builder.append(value);
return this;
}
/**
* Append a portion of a character sequence to the {@link StringBuilder}.
*
* @param value The character to append
* @param start The index of the first character
* @param end The index of the last character + 1
* @return This writer instance
*/
@Override
public Writer append(CharSequence value, int start, int end) {
builder.append(value, start, end);
return this;
}
/**
* Closing this writer has no effect.
*/
@Override
public void close() {
}
/**
* Flushing this writer has no effect.
*/
@Override
public void flush() {
}
/**
* Write a String to the {@link StringBuilder}.
*
* @param value The value to write
*/
@Override
public void write(String value) {
if (value != null) {
builder.append(value);
}
}
/**
* Write a portion of a character array to the {@link StringBuilder}.
*
* @param value The value to write
* @param offset The index of the first character
* @param length The number of characters to write
*/
@Override
public void write(char[] value, int offset, int length) {
if (value != null) {
builder.append(value, offset, length);
}
}
/**
* Return the underlying builder.
*
* @return The underlying builder
*/
public StringBuilder getBuilder() {
return builder;
}
/**
* Returns {@link StringBuilder#toString()}.
*
* @return The contents of the String builder.
*/
@Override
public String toString() {
return builder.toString();
}
}
按照主键的查询操作
final String ipAddress = "192.168.126.128";
final int port = 9200;
RestClient restClient;
@Before
public void init() {
restClient = MyElasticsearchUtils.openElasticsearchWithHttp(ipAddress, port);
}
public void printResponseEntity(Response response) {
try {
System.out.println(response);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String result = IOUtils.toString(is);
System.out.println(result);
} catch (UnsupportedOperationException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 测试查询数据,当查询一个不存在的文档的时候就会报错
@Test
public void testSelect() {
Request request = new Request("GET", "/accounts/person/2");
try {
Response response = restClient.performRequest(request);
printResponseEntity(response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
MyElasticsearchUtils.closeClient(restClient);
}
}
// 添加数据操作
@Test
public void testInsert() {
Request request = new Request("PUT", "/accounts/person/3");
request.setJsonEntity("{\"user\":\"王五\",\"title\":\"工程师\",\"desc\":\"数据库管理\"}");
try {
Response response = restClient.performRequest(request);
printResponseEntity(response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
MyElasticsearchUtils.closeClient(restClient);
}
}
// 修改数据操作
@Test
public void testUpdate() {
Request request = new Request("PUT", "/accounts/person/2");
request.setJsonEntity("{\"user\":\"李四\",\"title\":\"java工程师2\",\"desc\":\"java数据库管理\"}");
try {
Response response = restClient.performRequest(request);
printResponseEntity(response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
MyElasticsearchUtils.closeClient(restClient);
}
}
结果
@Test
public void testDelete() {
Request request = new Request("DELETE", "/accounts/person/3");
// request.setJsonEntity("{\"user\":\"李四\",\"title\":\"java工程师\",\"desc\":\"java数据库管理\"}");
try {
Response response = restClient.performRequest(request);
printResponseEntity(response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
MyElasticsearchUtils.closeClient(restClient);
}
}
// 使用条件查询
@Test
public void testSearchByCondition() {
Request request = new Request("GET", "/accounts/person/_search");
request.addParameter("q", "title:工程师");
try {
Response response = restClient.performRequest(request);
printResponseEntity(response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
MyElasticsearchUtils.closeClient(restClient);
}
}
@Test
public void testSearchPageByCondition() {
Request request = new Request("GET", "/accounts/person/_search");
request.addParameter("q", "title:工程师");
request.addParameter("from", "1");
request.addParameter("size", "1");
try {
Response response = restClient.performRequest(request);
printResponseEntity(response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
MyElasticsearchUtils.closeClient(restClient);
}
}
1.使用java方式操作Elasticsearch,对应的添加就是PUT,修改也是PUT,删除为DELETE,查询为GET
2.添加和修改数据的时候可以指定JSONBODY,这样就添加了json数据了
3.查询的时候可以使用_search和指定parameter的key为q,值为字段=某个值
,可以实现条件查询,如果添加from和size就可以实现分页了
4.删除和主键查询操作时如果主键id不存在,则引发异常
!
以上纯属个人见解,如有问题请联系本人!