【问题标题】:elasticlunr.js not showing results for search queryelasticlunr.js 不显示搜索查询的结果
【发布时间】:2017-02-14 07:44:12
【问题描述】:

我使用了elasticlunr.js 搜索引擎。

我编辑了他们的示例源代码

$('input').bind("enterKey", function (e) {

    var value_test = $("#inputSuccess1").val();

    if ($(this).val() < 2) return
    var config = $('#configuration').val();
    config.trim();
    var json_config = null;
    if (config != '') {
        json_config = new elasticlunr.Configuration(config, idx.getFields()).get();
    }

    var query = value_test;
    var results = null;

    console.log(query);

    if (json_config == null) {
        results = idx.search(query).map(function (result) {
            console.log(result);
            return questions.filter(function (q) {
                console.log(q);
                return q.page_id === parseInt(result.ref, 10)
            })[0]
        })
    } else {
        results = idx.search(query, json_config).map(function (result) {
            return questions.filter(function (q) {
                return q.page_id === parseInt(result.ref, 10)
            })[0]
        })
    }
    renderQuestionList(results);
    console.log(results);
});

所有存储的搜索结果都会在加载时显示,但是当我输入搜索查询时,它会返回假定的未编辑搜索结果。尽管搜索结果数组(例如)由 2 个 items 填充,但它仍然是未定义的。我尝试将自己的结果(只有 1 个)放在 example_index.json 上,并尝试输入与其相关的标签。还是不显示。

HTML 代码

<body>
<div id="wrapper">
    <main class="main" role="main" style="margin-top: 30px">
        <div class="container">
            <div class="row">
                <header style="margin-left: 15px; margin-right: 15px;">
                    <h1>Elasticlunr<span>.js</span></h1>
                    <h2>Lightweight full-text search engine in Javascript for browser search and offline search.</h2>
                </header>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <span><strong><i>Search Configuration:</i></strong></span>
                    <textarea id="configuration" class="form-control" rows="6" style="font-size: 0.8em;"></textarea>
                </div>

                <div class="col-md-6" style="margin-left: 0px; margin-right: 0px; padding-right: 0px; padding-left: 0px;">
                    <span><strong><i>Configuration Example:</i></strong></span>

                </div>
            </div>

            <div class="row" style="margin-left: 0px; margin-right: 0px; border-top-style: solid; border-top-width: 0px; padding-top: 10px;">
                <div class="col-md-6" style="padding-left: 0px; padding-right: 50px">
                    <form>
                        <div class="form-group has-success">
                            <div class="col-xs-9" style="padding-left: 0px;">
                                <input type="search" class="form-control" id="inputSuccess1" >
                            </div>
                        </div>
                        <div><a class="all btn btn-primary btn-block" href="#">All</a></div>
                    </form>
                </div>
                <div class="col-md-12" style="margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid rgba(7, 94, 115, 0.3); padding-left: 0px;"></div>
            </div>

            <div class="row" style="margin-left: 0px; margin-right: 0px;">
                <div class="col-md-6" style="margin-left: 0px; margin-right: 0px;">
                    <div id='question-list-container' style="margin-left: 0px; margin-right: 0px;"></div>
                </div>

                <div class="col-md-6" style="margin-left: 0px; margin-right: 0px; padding-right: 0px; padding-left: 0px;">
                    <div id='question-view-container' style="margin-left: 0px; margin-right: 0px; padding-right: 0px; padding-left: 0px;"></div>
                </div>
                <div class="col-md-12" style="padding-bottom: 15px; border-bottom:1px solid rgba(7,94,115,0.3);"></div>
            </div>
        </main>
    </div>
    <!-- end of wrapper -->

    <!-- Begin footer -->
    <footer class="footer vertical-center">
        <div class="container">
            <p class="pull-right text-muted"><a href="#">Back to top</a>
            </p>
            <p class="text-muted">Copyright &copy; Wei Song 2015.
                <a href="https://github.com/weixsong">https://github.com/weixsong</a> watkinsong@163.com.  Donate by Alipay: watkinsong@163.com</p>
        </div>
    </footer>

    <script>
        (function(hijs) {
            //
            // hijs - JavaScript Syntax Highlighter
            //
            // Copyright (c) 2010 Alexis Sellier
            //

            // All elements which match this will be syntax highlighted.
            var selector = hijs || 'pre';

            var keywords = ('var function if else for while break switch case do new null in with void ' + 'continue delete return this true false throw catch typeof with instanceof').split(' '),
                special = ('eval window document undefined NaN Infinity parseInt parseFloat ' + 'encodeURI decodeURI encodeURIComponent decodeURIComponent').split(' ');

            // Syntax definition
            // The key becomes the class name of the <span>
            // around the matched block of code.
            var syntax = [
                ['comment', /(\/\*(?:[^*\n]|\*+[^\/*])*\*+\/)/g],
                ['comment', /(\/\/[^\n]*)/g],
                ['string', /("(?:(?!")[^\\\n]|\\.)*"|'(?:(?!')[^\\\n]|\\.)*')/g],
                ['regexp', /(\/.+\/[mgi]*)(?!\s*\w)/g],
                ['class', /\b([A-Z][a-zA-Z]+)\b/g],
                ['number', /\b([0-9]+(?:\.[0-9]+)?)\b/g],
                ['keyword', new(RegExp)('\\b(' + keywords.join('|') + ')\\b', 'g')],
                ['special', new(RegExp)('\\b(' + special.join('|') + ')\\b', 'g')]
            ];
            var nodes, table = {};

            if (/^[a-z]+$/.test(selector)) {
                nodes = document.getElementsByTagName(selector);
            } else if (/^\.[\w-]+$/.test(selector)) {
                nodes = document.getElementsByClassName(selector.slice(1));
            } else if (document.querySelectorAll) {
                nodes = document.querySelectorAll(selector);
            } else {
                nodes = [];
            }

            for (var i = 0, children; i < nodes.length; i++) {
                children = nodes[i].childNodes;

                for (var j = 0, str; j < children.length; j++) {
                    code = children[j];

                    if (code.length >= 0) { // It's a text node
                        // Don't highlight command-line snippets
                        if (!/^\$/.test(code.nodeValue.trim())) {
                            syntax.forEach(function(s) {
                                var k = s[0],
                                    v = s[1];
                                code.nodeValue = code.nodeValue.replace(v, function(_, m) {
                                    return '\u00ab' + encode(k) + '\u00b7' + encode(m) +
                                        '\u00b7' + encode(k) + '\u00bb';
                                });
                            });
                        }
                    }
                }
            }
            for (var i = 0; i < nodes.length; i++) {
                nodes[i].innerHTML =
                    nodes[i].innerHTML.replace(/\u00ab(.+?)\u00b7(.+?)\u00b7\1\u00bb/g, function(_, name, value) {
                        value = value.replace(/\u00ab[^\u00b7]+\u00b7/g, '').replace(/\u00b7[^\u00bb]+\u00bb/g, '');
                        return '<span class="' + decode(name) + '">' + escape(decode(value)) + '</span>';
                    });
            }

            function escape(str) {
                return str.replace(/</g, '&lt;').replace(/>/g, '&gt;');
            }

            // Encode ASCII characters to, and from Braille
            function encode(str, encoded) {
                table[encoded = str.split('').map(function(s) {
                    if (s.charCodeAt(0) > 127) {
                        return s
                    }
                    return String.fromCharCode(s.charCodeAt(0) + 0x2800);
                }).join('')] = str;
                return encoded;
            }

            function decode(str) {
                if (str in table) {
                    return table[str];
                } else {
                    return str.trim().split('').map(function(s) {
                        if (s.charCodeAt(0) - 0x2800 > 127) {
                            return s
                        }
                        return String.fromCharCode(s.charCodeAt(0) - 0x2800);
                    }).join('');
                }
            }

        })(window.hijs);
    </script>

第三次编辑:

我有这个代码

$('input').keyup(function(e){
if(e.keyCode == 13)
{
    $(this).trigger("enterKey");
}

});

我使用 xampp,当我按下回车键时会发生这种情况。那些“空列表”来自以前的 .json 文件,但具有不同的 id 。我找不到那个部分

它有很多代码,所以我在这里上传(编辑:删除链接。现在修复)

【问题讨论】:

  • 可以提供fiddle或plunk吗?
  • 我会试着把它放进去
  • 我想我找到了现有链接的解决方案,但我现在就等着吧。
  • 我可以用 plunk 传输整个文件夹吗?你指的是 plnkr.co,对吧?
  • 只要是基于前端的。

标签: javascript jquery search


【解决方案1】:

input 标记存在于form 标记之间。这意味着在按下回车后,表单被提交,因此页面会重新加载,从而删除您放置的任何信息并显示纯正的结果。

在开发者提供的示例中,使用了$('input').bind('keyup', debounce(function () {。因此,在输入文本时,会搜索标签。但是,在您的情况下,控件甚至不会转移到您打算运行的代码。

请检查这个 https://jsfiddle.net/kaminasw/rqj68xt5/ 在输入中按回车时应显示警报。

$('input').bind("enterKey",function(e){
    alert();
});

尝试使用带有 keyup 事件的实际代码,并将按下的键与 enterKey 代码(即 13)进行比较。

$('input').keyup(function(e) {
    // 13 is ENTER
    if (e.which === 13)
    // Perform action
});

【讨论】:

  • 我在本地使用 xampp。我看到输入在表单内,但是,即使在表单内输入,它也可以工作,但它给了我空的结果(参见第 3 次编辑)。这很有帮助。在虚拟主机中。它做你刚才说的。它重新加载。谢谢你。
  • 要将答案标记为已接受,请单击答案旁边的复选标记以将其从灰色切换为已填充。
【解决方案2】:

我阅读了手册并错过了 node.js 部分。如您所见,index_builder.js 使用 fs,这是我学到的,它使用 node.js。您必须使用 node.js 并运行 index_builder.js。这将从您的 data.json(存储的搜索结果)构建一个 index.json 文件。该代码使用我必须重建索引的示例源代码。另外,我正在使用 xampp 作为本地主机。

Step 1. Download and Install node.js 
Step 2. Run Xampp Shell on elasticlunr project directory
Step 3. Type in node index_builder.js
Step 4. Elastic Search will work with the entered query

这是我的 index_builder.js 的代码

var elasticlunr = require('./elasticlunr.js'),
fs = require('fs');

var idx = elasticlunr(function () {
this.setRef('page_id');

this.addField('title');
this.addField('tags');
this.addField('body');
this.addField('url');
});



fs.readFile('./example_data.json', function (err, data) {
if (err) throw err;

var raw = JSON.parse(data);

var questions = raw.questions.map(function (q) {
return {
  page_id: q.page_id,
  title: q.title,
  body: q.body,
  url: q.url,
  tags: q.tags.join(' ')
  };
});

questions.forEach(function (question) {
idx.addDoc(question);
});

fs.writeFile('./example_index.json', JSON.stringify(idx), function (err) {
if (err) throw err;
console.log('done');
});
});

谢谢!

【讨论】:

    猜你喜欢
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多