可能的原因:
1、项目引用的ES版本和ES服务的版本不一样;
2、端口不正确,tcp访问端口是9300;
3、cluster.name不正确,可以通过访问http://localhost:9200/查看ES服务下的cluster.name;
4、ES服务没启动;
简单demo:
import java.net.InetAddress; import java.net.UnknownHostException; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.transport.client.PreBuiltTransportClient; public class ElasticDemo { //测试demo @SuppressWarnings({ "resource", "unchecked" }) public static void main(String[] aa) throws UnknownHostException { TransportClient client = null; Settings esSettings = Settings.builder() .put("cluster.name", "elasticsearch") //设置ES实例的名称 .build(); client = new PreBuiltTransportClient(esSettings) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); System.out.println("ElasticsearchClient 连接成功"); // BulkRequestBuilder bulkRequest = client.prepareBulk(); // try { // bulkRequest.add(client.prepareIndex("ko", "test", "14") // .setSource(jsonBuilder() // .startObject() // .field("tableId", "14") // .field("title", "tetstcccfffffccccccccccc") // .field("content", "ttttttttfffffffttttttttttt") // .endObject() // ) // ); // } catch (IOException e) { // e.printStackTrace(); // } // BulkResponse bulkResponse = bulkRequest.get(); // if (bulkResponse.hasFailures()) { // System.out.println("失败:" + bulkResponse.toString()); // } // System.out.println("操作成功"); HighlightBuilder highlightBuilder = new HighlightBuilder().field("title").requireFieldMatch(true); highlightBuilder.preTags("<span style="color:red">"); highlightBuilder.postTags("</span>"); highlightBuilder.boundaryMaxScan(4); SearchRequestBuilder searchRequestBuilder = client.prepareSearch("ko"); //可以是多个index //searchRequestBuilder.setQuery(QueryBuilders.termQuery("title", "ffff")); //精确查询 searchRequestBuilder.setQuery(QueryBuilders.wildcardQuery("title", "*文 el*")); //模糊查询 searchRequestBuilder.setFrom(0); searchRequestBuilder.setSize(2); searchRequestBuilder.highlighter(highlightBuilder); SearchResponse response = searchRequestBuilder.get(); System.out.println(response); } }