Saturday, September 27, 2014

Query Suggestions Webpart in SharePoint 2013

SharePoint Search suggestions are automatically generated: When users have clicked any of the search results for that query at least six times, then that query will be automatically added to search suggestions.Technically, on a daily basis, the SharePoint timer job titled "Prepare Query Suggestions" handles compiling them. So the automatic query suggestions can be different for different result sources and site collections.

We cannot retrieve those details in any OOB webpart.
For this , we need to create querysuggestion webpart programmatically:

Script:

<script src="/sites/Test/Style%20Library/JS/jquery-1.3.2.min.js" type="text/javascript"></script><!-- Load our custom Rest Search script file --><script src="/sites/Test/Style%20Library/JS/restSearch.js" type="text/javascript"></script><script type="text/javascript">
    $(document).ready(function () {
        var query = "test";
        $.ajax({
            type: "GET",
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/search/suggest?querytext='" + query + "'&fprequerysuggestions='true'",
            headers:
                    {
                        "accept": "application/json;odata=verbose",
                    },
            success: function (data) {
                var results = data.getElementsByTagName("d:Query");
                var html = "<div class='results'>";
                for (var i = 0; i < results.length; i++) {
                    var resultValue = (results[i].nodeTypedValue).replace(/[</B>]/ig, "")
                    html += "<div class='result-row' style='padding-bottom:5px;'>";
                    var clickableLink = "<a href='/sites/Test/Pages/searcgtest.aspx?k=" + resultValue + "'>" + resultValue + "</a><br/>";
                    html += clickableLink;
                    html += "</div>";
                }

                $("#suggestResults").html(html);
            },
            error: function (err) {
                $("#suggestResults").html("<h3>An error occured</h3><br/>" + JSON.stringify(err));
            }
        });
       
    });
</script>
   <div id="suggestResults">
   </div>

No comments:

Post a Comment