【问题标题】:Search text for matching large number of strings搜索匹配大量字符串的文本
【发布时间】:2017-07-04 11:39:05
【问题描述】:

我有一个用例,我必须检查作为输入接收的文本是否包含我拥有的 300 万个字符串中的任何一个。

我尝试了正则表达式匹配,但是一旦字符串列表超过 50k,性能就很差了

我对搜索列表中的每个单词都这样做

inText = java.util.regex.Pattern.compile("\\b" + findStr + "\\b",
         java.util.regex.Pattern.CASE_INSENSITIVE).matcher(intext).replaceAll(repl);

我知道我们可以使用像 lucene 这样的搜索索引,但我觉得这些索引主要用于从预定义文本中搜索特定文本,但我的用例恰恰相反,我需要发送一个大文本并检查是否有任何 pre文本中有定义的字符串

【问题讨论】:

    标签: search elasticsearch indexing lucene pattern-matching


    【解决方案1】:

    我想,你可以反过来看。您的预定义字符串是存储在倒排索引中的文档,而您的传入文本是一个查询,您将针对您的文档进行测试。由于预定义的字符串不会有太大变化,因此性能非常好。

    我准备了一些 Elasticsearch 代码,可以解决问题。

        public void add(String string, String id) {
            IndexRequest indexRequest = new IndexRequest(INDEX, TYPE, id);
            indexRequest.source(string);
            index(INDEX, TYPE, id, string);
        }
    
        @Test
        public void scoring() throws Exception {
            // adding your predefined strings
            add("{\"str\":\"string1\"}", "1");
            add("{\"str\":\"alice\"}", "2");
            add("{\"str\":\"bob\"}", "3");
            add("{\"str\":\"string2\"}", "4");
            add("{\"str\":\"melanie\"}", "5");
            add("{\"str\":\"moana\"}", "6");
    
            refresh(); // otherwise we would not anything
    
            indexExists(INDEX); // verifies that index exists
            ensureGreen(INDEX); // ensures cluster status is green
    
    
            // querying your text separated by space, if the hits length is bigger than 0, you're good
            SearchResponse searchResponse = client().prepareSearch(INDEX).setQuery(QueryBuilders.termsQuery("str", "string1", "string3", "melani")).execute().actionGet();
            SearchHit[] hits = searchResponse.getHits().getHits();
    
            assertThat(hits.length, equalTo(1));
    
            for (SearchHit hit: hits) {
                System.out.println(hit.getSource());
            }
    
        }
    

    【讨论】:

      猜你喜欢
      • 2015-01-18
      • 1970-01-01
      • 2020-06-17
      • 2018-04-09
      • 1970-01-01
      • 2012-12-10
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      相关资源
      最近更新 更多